Harbor format: 871 coding_baseline tasks (part 54)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/async.rst +188 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/changelog.rst +1765 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/code-of-conduct.rst +126 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/conf.py +193 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/copying.rst +348 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/developer.rst +130 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/features.rst +470 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/img/gui.png +3 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/index.rst +129 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/intro.rst +99 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/usage.rst +179 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/__init__.py +75 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/_version.py +24 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/archive.py +86 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/asyn.py +1335 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/caching.py +1158 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/callbacks.py +324 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/compression.py +185 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/config.py +131 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/conftest.py +125 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/core.py +765 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/dircache.py +125 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/exceptions.py +18 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/fuse.py +324 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/generic.py +409 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/gui.py +417 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/__init__.py +0 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/arrow.py +333 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/asyn_wrapper.py +135 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cache_mapper.py +75 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cache_metadata.py +217 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cached.py +1224 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/chained.py +23 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/dask.py +152 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/data.py +73 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/dbfs.py +498 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/dirfs.py +492 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/ftp.py +445 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/gist.py +241 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/git.py +123 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/github.py +348 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/http.py +1069 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/http_sync.py +937 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/ia.py +230 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/jupyter.py +132 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/libarchive.py +219 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/local.py +537 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/memory.py +476 -0
- tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/reference.py +1387 -0
.gitattributes
CHANGED
|
@@ -60,3 +60,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
data/tasks.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 62 |
tasks/tasksmith-35d8641e8647/tests/source/docs/_static/social[[:space:]]card.afdesign filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
data/tasks.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 62 |
tasks/tasksmith-35d8641e8647/tests/source/docs/_static/social[[:space:]]card.afdesign filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
tasks/tasksmith-4ca6d2396445/tests/source/docs/_static/social[[:space:]]card.afdesign filter=lfs diff=lfs merge=lfs -text
|
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/async.rst
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Async
|
| 2 |
+
=====
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
``fsspec`` supports asynchronous operations on certain implementations. This
|
| 7 |
+
allows for concurrent calls within bulk operations such as ``cat`` (fetch
|
| 8 |
+
the contents of many files at once) even from normal code, and for the direct
|
| 9 |
+
use of fsspec in async code without blocking.
|
| 10 |
+
Async implementations derive from the class ``fsspec.asyn.AsyncFileSystem``.
|
| 11 |
+
The class attribute ``async_impl`` can be used to test whether an
|
| 12 |
+
implementation is async of not.
|
| 13 |
+
|
| 14 |
+
``AsyncFileSystem`` contains ``async def`` coroutine versions of the methods of
|
| 15 |
+
``AbstractFileSystem``. By convention, these methods are prefixed with "_"
|
| 16 |
+
to indicate that they are not to called directly in normal code, only
|
| 17 |
+
when you know what you are doing. In most cases, the code is identical or
|
| 18 |
+
slightly modified by replacing sync calls with ``await`` calls to async
|
| 19 |
+
functions.
|
| 20 |
+
|
| 21 |
+
The only async implementation built into ``fsspec`` is ``HTTPFileSystem``.
|
| 22 |
+
|
| 23 |
+
Synchronous API
|
| 24 |
+
---------------
|
| 25 |
+
|
| 26 |
+
The methods of ``AbstractFileSystem`` are available and can be called from
|
| 27 |
+
normal code. They call and wait on the corresponding async function. The
|
| 28 |
+
*work* is carried out in a separate threads, so if there are many fsspec
|
| 29 |
+
operations in flight at once, launched from many threads, they will still
|
| 30 |
+
all be processed on the same IO-dedicated thread.
|
| 31 |
+
|
| 32 |
+
Most users should not be aware that their code is running async.
|
| 33 |
+
|
| 34 |
+
Note that the sync functions are wrapped using ``sync_wrapper``, which
|
| 35 |
+
copies the docstrings from ``AbstractFileSystem``, unless they are
|
| 36 |
+
explicitly given in the implementation.
|
| 37 |
+
|
| 38 |
+
Example:
|
| 39 |
+
|
| 40 |
+
.. code-block:: python
|
| 41 |
+
|
| 42 |
+
fs = fsspec.filesystem("http")
|
| 43 |
+
out = fs.cat([url1, url2, url3]) # fetches data concurrently
|
| 44 |
+
|
| 45 |
+
Coroutine batching
|
| 46 |
+
------------------
|
| 47 |
+
|
| 48 |
+
The various methods which create many coroutines to be passed to the event loop
|
| 49 |
+
for processing may be batched: submitting a certain number in one go and waiting
|
| 50 |
+
for them to complete before launching more. This is important to work around
|
| 51 |
+
local open-file limits (which can be <~100) and not to swamp the heap.
|
| 52 |
+
|
| 53 |
+
``fsspec.asyn._run_coros_in_chunks`` controls this process, but from the user's point
|
| 54 |
+
of view, there are three ways to affect it. In increasing order or precedence:
|
| 55 |
+
|
| 56 |
+
- the global variables ``fsspec.asyn._DEFAULT_BATCH_SIZE`` and
|
| 57 |
+
``fsspec.asyn._NOFILES_DEFAULT_BATCH_SIZE`` (for calls involving local files or not,
|
| 58 |
+
respectively)
|
| 59 |
+
|
| 60 |
+
- config keys "gather_batch_size" and "nofiles_gather_batch_size"
|
| 61 |
+
|
| 62 |
+
- the ``batch_size`` keyword, accepted by the batch methods of an async filesystem.
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
Using from Async
|
| 66 |
+
----------------
|
| 67 |
+
|
| 68 |
+
File system instances can be created with ``asynchronous=True``. This
|
| 69 |
+
implies that the instantiation is happening within a coroutine, so
|
| 70 |
+
the various async method can be called directly with ``await``, as is
|
| 71 |
+
normal in async code.
|
| 72 |
+
|
| 73 |
+
Note that, because ``__init__`` is a blocking function, any creation
|
| 74 |
+
of asynchronous resources will be deferred. You will normally need to
|
| 75 |
+
explicitly ``await`` a coroutine to create them. Since garbage collection
|
| 76 |
+
also happens in blocking code, you may wish to explicitly await
|
| 77 |
+
resource destructors too. Example:
|
| 78 |
+
|
| 79 |
+
.. code-block:: python
|
| 80 |
+
|
| 81 |
+
async def work_coroutine():
|
| 82 |
+
fs = fsspec.filesystem("http", asynchronous=True)
|
| 83 |
+
session = await fs.set_session() # creates client
|
| 84 |
+
out = await fs._cat([url1, url2, url3]) # fetches data concurrently
|
| 85 |
+
await session.close() # explicit destructor
|
| 86 |
+
|
| 87 |
+
asyncio.run(work_coroutine())
|
| 88 |
+
|
| 89 |
+
Bring your own loop
|
| 90 |
+
-------------------
|
| 91 |
+
|
| 92 |
+
For the non-asynchronous case, ``fsspec`` will normally create an asyncio
|
| 93 |
+
event loop on a specific thread. However, the calling application may prefer
|
| 94 |
+
IO processes to run on a loop that is already around and running (in another
|
| 95 |
+
thread). The loop needs to be asyncio compliant, but does not necessarily need
|
| 96 |
+
to be an ``ayncio.events.AbstractEventLoop``. Example:
|
| 97 |
+
|
| 98 |
+
.. code-block:: python
|
| 99 |
+
|
| 100 |
+
loop = ... # however a loop was made, running on another thread
|
| 101 |
+
fs = fsspec.filesystem("http", loop=loop)
|
| 102 |
+
out = fs.cat([url1, url2, url3]) # fetches data concurrently
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
Implementing new backends
|
| 106 |
+
-------------------------
|
| 107 |
+
|
| 108 |
+
Async file systems should derive from ``AsyncFileSystem``, and implement the
|
| 109 |
+
``async def _*`` coroutines there. These functions will either have sync versions
|
| 110 |
+
automatically generated if the name is in the ``async_methods`` list, or
|
| 111 |
+
can be directly created using ``sync_wrapper``.
|
| 112 |
+
|
| 113 |
+
.. code-block:: python
|
| 114 |
+
|
| 115 |
+
class MyFileSystem(AsyncFileSystem):
|
| 116 |
+
|
| 117 |
+
async def _my_method(self):
|
| 118 |
+
...
|
| 119 |
+
|
| 120 |
+
my_method = sync_wrapper(_my_method)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
These functions must **not call** methods or functions which themselves are synced,
|
| 124 |
+
but should instead ``await`` other coroutines. Calling methods which do not require sync,
|
| 125 |
+
such as ``_strip_protocol`` is fine.
|
| 126 |
+
|
| 127 |
+
Note that ``__init__``, cannot be ``async``, so it might need to allocate async
|
| 128 |
+
resources using the ``sync`` function, but *only* if ``asynchronous=False``. If it
|
| 129 |
+
is ``True``, you probably need to require the caller to await a coroutine that
|
| 130 |
+
creates those resources. Similarly, any destructor (e.g., ``__del__``) will run from normal
|
| 131 |
+
code, and possibly after the loop has stopped/closed.
|
| 132 |
+
|
| 133 |
+
To call ``sync``, you will need to pass the associated event loop, which will be
|
| 134 |
+
available as the attribute ``.loop``.
|
| 135 |
+
|
| 136 |
+
.. autosummary::
|
| 137 |
+
fsspec.asyn.AsyncFileSystem
|
| 138 |
+
fsspec.asyn.get_loop
|
| 139 |
+
fsspec.asyn.sync
|
| 140 |
+
fsspec.asyn.sync_wrapper
|
| 141 |
+
|
| 142 |
+
.. autoclass:: fsspec.asyn.AsyncFileSystem
|
| 143 |
+
:members:
|
| 144 |
+
|
| 145 |
+
.. autofunction:: fsspec.asyn.get_loop
|
| 146 |
+
|
| 147 |
+
.. autofunction:: fsspec.asyn.sync
|
| 148 |
+
|
| 149 |
+
.. autofunction:: fsspec.asyn.sync_wrapper
|
| 150 |
+
|
| 151 |
+
.. raw:: html
|
| 152 |
+
|
| 153 |
+
<script data-goatcounter="https://fsspec.goatcounter.com/count"
|
| 154 |
+
async src="//gc.zgo.at/count.js"></script>
|
| 155 |
+
|
| 156 |
+
AsyncFileSystemWrapper
|
| 157 |
+
----------------------
|
| 158 |
+
|
| 159 |
+
The `AsyncFileSystemWrapper` class allows you to convert
|
| 160 |
+
a synchronous filesystem into an asynchronous one. This is useful for quickly integrating
|
| 161 |
+
synchronous filesystems into workflows that may expect `AsyncFileSystem` instances.
|
| 162 |
+
|
| 163 |
+
Basic Usage
|
| 164 |
+
~~~~~~~~~~~
|
| 165 |
+
|
| 166 |
+
To use `AsyncFileSystemWrapper`, wrap any synchronous filesystem to work in an asynchronous context.
|
| 167 |
+
In this example, the synchronous `LocalFileSystem` is wrapped, creating an `AsyncFileSystem` instance
|
| 168 |
+
backed by the normal, synchronous methods of `LocalFileSystem`:
|
| 169 |
+
|
| 170 |
+
.. code-block:: python
|
| 171 |
+
|
| 172 |
+
import asyncio
|
| 173 |
+
import fsspec
|
| 174 |
+
from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
|
| 175 |
+
|
| 176 |
+
async def async_copy_file():
|
| 177 |
+
sync_fs = fsspec.filesystem('file') # by-default synchronous, local filesystem
|
| 178 |
+
async_fs = AsyncFileSystemWrapper(sync_fs)
|
| 179 |
+
return await async_fs._copy('/source/file.txt', '/destination/file.txt')
|
| 180 |
+
|
| 181 |
+
asyncio.run(async_copy_file())
|
| 182 |
+
|
| 183 |
+
Limitations
|
| 184 |
+
-----------
|
| 185 |
+
|
| 186 |
+
Users should not expect this wrapper to magically make things faster.
|
| 187 |
+
It is primarily provided to allow usage of synchronous filesystems with interfaces that exp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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Changelog
|
| 2 |
+
=========
|
| 3 |
+
|
| 4 |
+
Dev
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
Enhancements
|
| 8 |
+
|
| 9 |
+
- Accept a ``callback=`` on the caching filesystems and pass it to the ``get``
|
| 10 |
+
operations that fill the cache on a miss, so ``filecache``/``simplecache``
|
| 11 |
+
opens can report download progress (#1623)
|
| 12 |
+
|
| 13 |
+
Fixes
|
| 14 |
+
|
| 15 |
+
- Reject Git paths below files and preserve complete file names in Git metadata.
|
| 16 |
+
|
| 17 |
+
- Honor exclusive creation mode in DBFS file opens instead of overwriting an
|
| 18 |
+
existing file.
|
| 19 |
+
|
| 20 |
+
- Honor ``create_parents=False`` in ``MemoryFileSystem.mkdir`` when the parent
|
| 21 |
+
directory does not exist.
|
| 22 |
+
|
| 23 |
+
- Leave out the passwords of nested FSs when serializing with ``include_password=False``.
|
| 24 |
+
|
| 25 |
+
- Raise an error when WebHDFS refuses a rename instead of reporting success (#2327).
|
| 26 |
+
|
| 27 |
+
- Close local transactional write handles before deleting their temporary files
|
| 28 |
+
during rollback, avoiding Windows sharing errors and leaked handles.
|
| 29 |
+
|
| 30 |
+
- Omit unreachable references from ``ReferenceFileSystem.cat`` results when
|
| 31 |
+
``on_error="omit"``.
|
| 32 |
+
|
| 33 |
+
- Reject reads on closed asynchronous HTTP streams without reopening a request.
|
| 34 |
+
|
| 35 |
+
- Preserve explicit directory permissions when SFTP ``mkdir`` creates parents.
|
| 36 |
+
|
| 37 |
+
- Only send ``ia://`` credentials over https when the download URL is https.
|
| 38 |
+
|
| 39 |
+
- Honor ``block_size=0`` for direct and transactional SFTP file opens.
|
| 40 |
+
|
| 41 |
+
- Make FUSE CLI ``-f`` match its documented default (#1586).
|
| 42 |
+
|
| 43 |
+
- Preserve source and destination URL text within relative names during ``generic.rsync``.
|
| 44 |
+
|
| 45 |
+
- Accept equivalent binary update mode orderings in ``MemoryFileSystem.open``.
|
| 46 |
+
|
| 47 |
+
- Request a protected data channel again when ``FTPFileSystem`` reconnects
|
| 48 |
+
with ``tls=True``
|
| 49 |
+
|
| 50 |
+
- Decompress cache downloads made by ``cat`` so
|
| 51 |
+
subsequent cached reads use the same contents as ``open``.
|
| 52 |
+
|
| 53 |
+
- Retain the selected local file when a ``filecache`` entry expires during open.
|
| 54 |
+
|
| 55 |
+
- Fix the syntax and add a memory filesystem to the quick-start example (#2337).
|
| 56 |
+
|
| 57 |
+
- Preserve directory pruning in ``DirFileSystem.walk(detail=True)``
|
| 58 |
+
|
| 59 |
+
- Finalize zip-fs file contexts on explicit close (#2311).
|
| 60 |
+
|
| 61 |
+
- Close sync HTTP download files on success or failure, without closing caller-owned streams.
|
| 62 |
+
|
| 63 |
+
- Expose known buffered-file sizes through a ``len`` property for multipart encoders.
|
| 64 |
+
|
| 65 |
+
- Propagate backend removal errors from ``FSMap``
|
| 66 |
+
|
| 67 |
+
- Check known_hosts in ``SFTPFileSystem`` (#2308; issue #2119)
|
| 68 |
+
|
| 69 |
+
- Warn with the fingerprint when ``SFTPFileSystem`` accepts an unknown host
|
| 70 |
+
key, and add the key to ``known_hosts`` if it is given (#2308)
|
| 71 |
+
|
| 72 |
+
- Require ``paramiko>=3.4`` for the ``sftp`` and ``ssh`` extras (#2308)
|
| 73 |
+
- Handle explicit ``create`` and ``overwrite`` modes in ZIP ``pipe``
|
| 74 |
+
|
| 75 |
+
- Bound block-cache fetch ranges by the file size, including background reads.
|
| 76 |
+
|
| 77 |
+
- Drain pending adaptive prefetch tasks on close after the producer reaches EOF.
|
| 78 |
+
|
| 79 |
+
- Exclude URL fragments when decoding data URLs.
|
| 80 |
+
|
| 81 |
+
- Return empty results for HTTP reads ending at offset zero without sending an invalid range request.
|
| 82 |
+
|
| 83 |
+
- Correct the configuration directory variable and explain JSON parsing of environment overrides (#2324)
|
| 84 |
+
|
| 85 |
+
- Update contributor linting and formatting instructions for Ruff and pre-commit (#2325)
|
| 86 |
+
|
| 87 |
+
- Accept string-valued path-like objects in ``DirFileSystem`` delegated operations.
|
| 88 |
+
|
| 89 |
+
- Reject mixed source or destination backends in ``GenericFileSystem.copy``(#2302).
|
| 90 |
+
|
| 91 |
+
- Return the current position for accepted no-op seeks on HTTP streams (#2306)
|
| 92 |
+
|
| 93 |
+
- Complete DBFS partial-delete retries without re-raising a recovered error.
|
| 94 |
+
|
| 95 |
+
- Keep the HTTP link regex linear
|
| 96 |
+
|
| 97 |
+
- Preserve single-source copy semantics for Paths in sync batch ops
|
| 98 |
+
|
| 99 |
+
- Reject unsupported HTTP ``pipe_file`` modes defensively before writing,
|
| 100 |
+
since PUT behavior depends on the server (#2294).
|
| 101 |
+
|
| 102 |
+
- Reject ``generic.rsync`` source names whose ".." segments would place
|
| 103 |
+
copies outside the destination
|
| 104 |
+
|
| 105 |
+
- Avoid reference cycles when a synchronous call into an async filesystem
|
| 106 |
+
fails, so its frames and the data they hold are freed straight away instead
|
| 107 |
+
of waiting for the garbage collector (#2295)
|
| 108 |
+
|
| 109 |
+
- Reject read-only buffers in buffered-file ``readinto()`` before consuming file data (#2260)
|
| 110 |
+
|
| 111 |
+
- Honor ``maxdepth`` when copying recursively with ``ReferenceFileSystem.get``. (#2269)
|
| 112 |
+
|
| 113 |
+
- Support ``length=None`` in ``utils.read_block`` without a delimiter (#2262)
|
| 114 |
+
|
| 115 |
+
- Reject memory fs copies whose destination conflicts with an existing
|
| 116 |
+
file or directory (#2268)
|
| 117 |
+
|
| 118 |
+
- Preserve ``None`` values when serializing filesystem arguments (#2264)
|
| 119 |
+
|
| 120 |
+
- Correct file name padding for large integer maxima so lexical order matches numeric order (#2263)
|
| 121 |
+
|
| 122 |
+
- Preserve caller-owned protocol options when merging per-call overrides (#2279)
|
| 123 |
+
|
| 124 |
+
- Return an empty block instead of passing a negative read length in read_block (#2261)
|
| 125 |
+
|
| 126 |
+
- Preserve per-call request options in HTTP directory listings (#2258)
|
| 127 |
+
|
| 128 |
+
- Refetch memory-mapped cache blocks when a missing backing file is recreated (#2257)
|
| 129 |
+
|
| 130 |
+
- Normalize single-dot and empty path components in libarchive member names and lookups.
|
| 131 |
+
|
| 132 |
+
- Read the last libarchive member consistently when duplicate names include empty files.
|
| 133 |
+
|
| 134 |
+
- Preserve caller-provided temporary directories during cross-filesystem copies.
|
| 135 |
+
|
| 136 |
+
- Raise ``FileExistsError`` when ``MemoryFileSystem.makedirs`` targets an existing file, even with ``exist_ok=True`` (#2266).
|
| 137 |
+
|
| 138 |
+
- Close memory-mapped cache resources when the owning buffered file is closed.
|
| 139 |
+
|
| 140 |
+
- Use the correct POST method in the Pyodide HTTP session shim.
|
| 141 |
+
|
| 142 |
+
- Decode URL-escaped base64 payloads in data URLs and distinguish the encoding flag from MIME metadata.
|
| 143 |
+
|
| 144 |
+
- Read empty GitHub files without requiring the HTTP extra or a second download.
|
| 145 |
+
|
| 146 |
+
- Accept PathLike local destinations in synchronous ``get`` (#896).
|
| 147 |
+
|
| 148 |
+
- Reject seeks that change position on async streaming HTTP files.
|
| 149 |
+
|
| 150 |
+
- Follow GitHub API pagination when listing tags, branches and repositories.
|
| 151 |
+
|
| 152 |
+
- Strip SFTP and SSH URL prefixes before recursively creating directories.
|
| 153 |
+
|
| 154 |
+
- Return ``created`` as a timestamp in ``MemoryFileSystem.info``, as ``ls`` and ``find`` already do.
|
| 155 |
+
|
| 156 |
+
- Strip the protocol from the path in ``LocalFileSystem.lexists``.
|
| 157 |
+
|
| 158 |
+
- Preserve Windows drive letters when parsing Git filesystem URLs (#1125).
|
| 159 |
+
|
| 160 |
+
- Return a list of paths when listing a single file with ``GithubFileSystem``.
|
| 161 |
+
|
| 162 |
+
- Recognize multi-byte delimiters spanning read blocks in buffered-file ``readuntil()``.
|
| 163 |
+
|
| 164 |
+
- Stop the fsspec IO loop and join its thread at interpreter exit, so a callback firing on it after ``Py_Finalize`` (e.g. a uvloop timer)
|
| 165 |
+
cannot crash the process (#2241).
|
| 166 |
+
|
| 167 |
+
- Avoid deadlocks in ``sync()`` when the default IO thread has stopped (#1723).
|
| 168 |
+
|
| 169 |
+
- Percent-encode GitHub branch and tag names in API URLs so refs containing ``#``, ``&`` or ``%`` select the intended revision.
|
| 170 |
+
|
| 171 |
+
- Keep files deeper than ``maxdepth`` in a recursive ``LocalFileSystem.rm`` instead of deleting the whole tree.
|
| 172 |
+
|
| 173 |
+
- Keep directories that still hold files deeper than ``maxdepth`` in a recursive ``MemoryFileSystem.rm`` instead of raising ``OSError``.
|
| 174 |
+
|
| 175 |
+
- Read ini and json config files as UTF-8 instead of the locale encoding.
|
| 176 |
+
|
| 177 |
+
- Infer Zstandard compression for ``.zstd`` as well as ``.zst`` (#1589).
|
| 178 |
+
|
| 179 |
+
- Keep files deeper than ``maxdepth`` in the source of a recursive ``mv`` instead of deleting them uncopied.
|
| 180 |
+
|
| 181 |
+
- Accept local filesystem URLs in ``get_file`` when copying to a file-like object.
|
| 182 |
+
|
| 183 |
+
- Accept full FTP URLs in direct ``cat_file`` and ``get_file`` calls.
|
| 184 |
+
|
| 185 |
+
- Strip the protocol from the path in ``LocalFileSystem.chmod``.
|
| 186 |
+
|
| 187 |
+
- Forward the wrapped filesystem's ``local_file`` flag through ``DirFileSystem`` (#1110).
|
| 188 |
+
|
| 189 |
+
- Report ``DirFileSystem.async_impl`` from the wrapped filesystem instance.
|
| 190 |
+
|
| 191 |
+
- Request identity encoding for buffered HTTP range reads by default, while
|
| 192 |
+
preserving explicitly configured request and session encodings (#1748).
|
| 193 |
+
|
| 194 |
+
- Avoid treating content-encoded transfer lengths as decoded file sizes in
|
| 195 |
+
the synchronous HTTP filesystem.
|
| 196 |
+
|
| 197 |
+
- Resolve negative FTP read offsets relative to the end of the file.
|
| 198 |
+
|
| 199 |
+
- Return an empty list from buffered-file ``readlines()`` at end of file
|
| 200 |
+
|
| 201 |
+
- Normalize protocol prefixes and leading slashes before listing archive paths.
|
| 202 |
+
|
| 203 |
+
- Update memory file modification times after writes and truncation.
|
| 204 |
+
|
| 205 |
+
- Preserve binary bytes in percent-encoded data URLs without base64 encoding.
|
| 206 |
+
|
| 207 |
+
- Keep failed memory-mapped cache reads retriable without discarding completed ranges.
|
| 208 |
+
|
| 209 |
+
- Percent-encode GitHub file paths in contents API URLs so files named with ``#``, ``?`` or ``%`` can be read and removed.
|
| 210 |
+
|
| 211 |
+
- Make async loop lock initialization thread-safe (#1783)
|
| 212 |
+
|
| 213 |
+
- Create parent directories before ``FSMap.setitems`` writes, matching ``__setitem__``
|
| 214 |
+
and allowing deferred local transaction writes to commit to missing parents (#1041).
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
2026.9.0
|
| 218 |
+
--------
|
| 219 |
+
|
| 220 |
+
Enhancements
|
| 221 |
+
|
| 222 |
+
- ``ia://`` filesystem for files in Internet Archive items: an
|
| 223 |
+
``HTTPFileSystem`` reading from ``archive.org/download`` with credentials from
|
| 224 |
+
``ia configure``'s ``ia.ini``
|
| 225 |
+
- Allow instance-local memory stores with ``global_store=False`` while
|
| 226 |
+
preserving normal instance caching and the default shared store (#2137;
|
| 227 |
+
issue #1904)
|
| 228 |
+
|
| 229 |
+
- Add an adaptive readahead cache (#2093)
|
| 230 |
+
|
| 231 |
+
- Implement ``created`` and ``modified`` for ``SFTPFileSystem`` (#2104)
|
| 232 |
+
|
| 233 |
+
- Allow filesystem implementations to assign ``protocol`` per instance (#2117)
|
| 234 |
+
|
| 235 |
+
- Delegate ``sizes`` and ``cat_ranges`` from ``DirFileSystem`` to the wrapped
|
| 236 |
+
filesystem (#2142)
|
| 237 |
+
|
| 238 |
+
- Delegate ``invalidate_cache``, ``ukey`` and ``checksum`` from
|
| 239 |
+
``DirFileSystem`` to the wrapped filesystem (#2144)
|
| 240 |
+
|
| 241 |
+
- Support negative offsets in ``TarFileSystem.cat_file`` (#2146)
|
| 242 |
+
|
| 243 |
+
- Mirror ``readinto`` from the PyArrow stream onto ``ArrowFile`` (#2111)
|
| 244 |
+
|
| 245 |
+
- Allow ``simplecache`` files to be removed by age using their modification
|
| 246 |
+
times (#2118)
|
| 247 |
+
|
| 248 |
+
- HTTP: retry transient failures (408/425/429/5xx, dropped connections,
|
| 249 |
+
timeouts, truncated range bodies, a 416 inside the file) of ``cat_file``,
|
| 250 |
+
``HTTPFile`` block reads and the size lookup behind ``open``, controlled
|
| 251 |
+
by the new ``retries``,
|
| 252 |
+
``retry_wait``, ``retry_statuses`` and ``retry_exceptions`` options
|
| 253 |
+
(#2124)
|
| 254 |
+
|
| 255 |
+
Fixes
|
| 256 |
+
|
| 257 |
+
- Compute ``HadoopFileSystem.fsid`` from its configured host and port instead of
|
| 258 |
+
accessing attributes no longer exposed by PyArrow (issue #1870)
|
| 259 |
+
|
| 260 |
+
- Normalize dot path components in ``TarFileSystem`` listings and lookups,
|
| 261 |
+
while preserving original archive names for reading (issue #1568)
|
| 262 |
+
|
| 263 |
+
- Make ``merge_offset_ranges`` ``O(n log n)`` and keep merged blocks within
|
| 264 |
+
``max_block``, replacing the quadratic nested-range filter added in #1982
|
| 265 |
+
(#2091)
|
| 266 |
+
|
| 267 |
+
- Fix transactions with compressed files (#2070)
|
| 268 |
+
|
| 269 |
+
- Make ``MemoryFileSystem.rm`` raise ``FileNotFoundError`` for a path that does
|
| 270 |
+
not exist, as ``rm_file`` and the other filesystems do, so deleting a missing
|
| 271 |
+
key from a memory-backed mapper raises ``KeyError`` (#2140)
|
| 272 |
+
|
| 273 |
+
- Create missing ZIP archives in append mode without truncating existing
|
| 274 |
+
archives (#2139)
|
| 275 |
+
|
| 276 |
+
- Close cached readers when exiting an ``open_files`` context (#2131)
|
| 277 |
+
|
| 278 |
+
- Avoid mutating live ``BlockCache`` and ``BackgroundBlockCache`` instances
|
| 279 |
+
when pickling (#2102)
|
| 280 |
+
|
| 281 |
+
- End the transaction even when a commit or discard raises, so the filesystem
|
| 282 |
+
is not left in transaction mode and deferred temporary files are cleaned up
|
| 283 |
+
(#2108)
|
| 284 |
+
|
| 285 |
+
- Honor a caller-owned output file in ``get_file`` (#2066)
|
| 286 |
+
|
| 287 |
+
- Preserve existing files when checking ``FSMap`` write access (#2122)
|
| 288 |
+
|
| 289 |
+
- Normalize ZIP paths in ``pipe_file`` and ``find`` (#2123)
|
| 290 |
+
|
| 291 |
+
- Reject ``get`` destinations that resolve above the target (#2103)
|
| 292 |
+
|
| 293 |
+
- Pass ``maxdepth`` through in ``AsyncFileSystem._rm`` (#2106)
|
| 294 |
+
|
| 295 |
+
- Do not let ``isfile`` swallow ``BaseException`` (#2125)
|
| 296 |
+
|
| 297 |
+
- Keep reference filesystem ``get`` destinations inside the target (#2129)
|
| 298 |
+
|
| 299 |
+
- Return relative names from ``DirFileSystem.glob`` and ``find`` (#2127)
|
| 300 |
+
|
| 301 |
+
- Raise ``FileNotFoundError`` for missing ZIP and TAR members (#2141)
|
| 302 |
+
|
| 303 |
+
- Stop collapsing three-character drive-relative paths to the drive root
|
| 304 |
+
(#2143)
|
| 305 |
+
|
| 306 |
+
- Use ``/`` as the only glob separator on every platform (#2112)
|
| 307 |
+
|
| 308 |
+
- Distinguish omitted and ``None`` defaults in ``FSMap.pop`` (#2136)
|
| 309 |
+
|
| 310 |
+
- Forward an Arrow file's ``flush`` and ``closed`` state to its stream (#2134)
|
| 311 |
+
|
| 312 |
+
- Keep reference filesystem ``cat_file`` offsets inside the referenced part
|
| 313 |
+
(#2147)
|
| 314 |
+
|
| 315 |
+
- Raise ``FileNotFoundError`` from archive ``ls`` for a missing path (#2145)
|
| 316 |
+
|
| 317 |
+
- Download uncached files in ``simplecache.cat_ranges`` (#2154)
|
| 318 |
+
|
| 319 |
+
- Fix ``tail`` on ``simplecache`` and ``filecache`` (#2155)
|
| 320 |
+
|
| 321 |
+
- Get whole-file reference sizes asynchronously in
|
| 322 |
+
``ReferenceFileSystem._info`` (#2156)
|
| 323 |
+
|
| 324 |
+
- Report the target size for links in ``TarFileSystem`` (#2157)
|
| 325 |
+
|
| 326 |
+
- Keep the async generator returned by ``AsyncFileSystemWrapper._walk``
|
| 327 |
+
(#2158)
|
| 328 |
+
|
| 329 |
+
- Join the default output filename with ``/`` in ``_expand_paths`` (#2162)
|
| 330 |
+
|
| 331 |
+
- Make names relative in ``DirFileSystem.walk(detail=True)`` (#2160)
|
| 332 |
+
|
| 333 |
+
- Ignore a leading slash in ``TarFileSystem`` paths (#2148)
|
| 334 |
+
|
| 335 |
+
- Fix ``cat_ranges`` on whole-file caches (#2163)
|
| 336 |
+
|
| 337 |
+
- Normalize paths in ``AsyncFileSystemWrapper`` like the wrapped filesystem
|
| 338 |
+
(#2159)
|
| 339 |
+
|
| 340 |
+
- The SFTP host key policy is configurable with the new ``host_key_policy``
|
| 341 |
+
argument of ``SFTPFileSystem``, which accepts ``"auto_add"`` (default,
|
| 342 |
+
unchanged behaviour), ``"warning"`` or ``"reject"``, or any
|
| 343 |
+
``paramiko.MissingHostKeyPolicy`` (#2126; issue #2119)
|
| 344 |
+
|
| 345 |
+
Other
|
| 346 |
+
|
| 347 |
+
- Use trusted publishing for releases and trigger the release workflow on tags
|
| 348 |
+
(#2060)
|
| 349 |
+
|
| 350 |
+
- Remove the stale async wrapper documentation warning (#2098)
|
| 351 |
+
|
| 352 |
+
- Add Zarr to the ``test_downstream`` extra so the Xarray/Zarr test runs again
|
| 353 |
+
(#2109)
|
| 354 |
+
|
| 355 |
+
- Clarify that ``rm`` handles directories (#2096)
|
| 356 |
+
|
| 357 |
+
- Fix grammar in ``features.rst`` (#2153)
|
| 358 |
+
|
| 359 |
+
- Patch ``HAS_CPYTHON_API`` where ``_fast_slice`` reads it in tests (#2164)
|
| 360 |
+
|
| 361 |
+
- Percent-decode the username and password parsed from URLs in
|
| 362 |
+
``infer_storage_options`` so that backends (ftp, sftp, smb, ...) receive
|
| 363 |
+
the real credentials rather than their URL-encoded form; a password whose
|
| 364 |
+
bare ``%`` produces bytes that are not valid UTF-8 (for example
|
| 365 |
+
``pass%ab``) is left untouched so that pre-existing URLs with unescaped
|
| 366 |
+
``%`` continue to work (#1871)
|
| 367 |
+
|
| 368 |
+
2026.7.0
|
| 369 |
+
--------
|
| 370 |
+
|
| 371 |
+
Enhancements
|
| 372 |
+
|
| 373 |
+
- Single-pass ``MemoryFileSystem.find()`` to avoid O(n_dirs * n_entries) listing (#2055)
|
| 374 |
+
- Permit composite URL protocol schemes in infer_storage_options (#2085)
|
| 375 |
+
- Implement topdown in async walk() (#2052)
|
| 376 |
+
|
| 377 |
+
Fixes
|
| 378 |
+
|
| 379 |
+
- Fix incorrect glob docstring for '[!]' (#2084)
|
| 380 |
+
- Propagate storage_options to all backends resolved by GenericFileSystem (#2083)
|
| 381 |
+
- Handle end=None in FirstChunkCache._fetch like the other caches (#2082)
|
| 382 |
+
- Clamp read end to file size in BlockCache and BackgroundBlockCache(#2081)
|
| 383 |
+
- Create the parent dir for "x" and "a" modes under auto_mkdir (#2079)
|
| 384 |
+
- Expand paths for mode="x" when urlpath is a list (#2078)
|
| 385 |
+
- fix: correctly pass 'start' and 'end' parameters to super().cat_file() (#2077)
|
| 386 |
+
- Fix LocalFileSystem directory symlink removal (#2074)
|
| 387 |
+
- Fix ArrowFSWrapper parent paths for S3 (#2072)
|
| 388 |
+
- Fix get_file_extension when a parent directory name contains a dot (#2071)
|
| 389 |
+
- tar: make members with duplicate slashes reachable via ls/find/glob (#2063)
|
| 390 |
+
- MemoryFileSystem: create the file when appending to a missing path (#2062)
|
| 391 |
+
|
| 392 |
+
Other
|
| 393 |
+
|
| 394 |
+
- fixes for pytest deprecation (#2076)
|
| 395 |
+
- Shut down background cache workers on file close (#2069)
|
| 396 |
+
- Forward ls kwargs from cached filesystems (#2068)
|
| 397 |
+
- Fix bare except: use except Exception in upload cleanup handler (#2067)
|
| 398 |
+
- fix: Make Cached metaclass instance instantiation thread-safe and fork-safe (#2064)
|
| 399 |
+
- ci: fix test collection in fsspec_friends job (#2061)
|
| 400 |
+
- ftp: Make deprecated TLS versions optional (#2056)
|
| 401 |
+
- restrict cache storage directory permissions to owner (#2048)
|
| 402 |
+
|
| 403 |
+
2026.6.0
|
| 404 |
+
--------
|
| 405 |
+
|
| 406 |
+
Fixes
|
| 407 |
+
|
| 408 |
+
- FTP: preserve filenames containing whitespace in _mlsd2 (#2043)
|
| 409 |
+
- Prevent attribute error for 'forced' before flushing cache (#2042)
|
| 410 |
+
- Reflect async _walk correctly (#2040)
|
| 411 |
+
- Fix infinite recursion in expand_path with glob magic characters (#2038)
|
| 412 |
+
- Do not strip trailing slashes from data URIs (#2037)
|
| 413 |
+
- Fix referenceFS for new zarr and pandas (#2034)
|
| 414 |
+
- Omit get_ident() from cache token for async impl in sync mode (#2028)
|
| 415 |
+
|
| 416 |
+
Other
|
| 417 |
+
|
| 418 |
+
- Fix AsyncFileSystem._cat_ranges on_error handling (#2045)
|
| 419 |
+
- Forward kwargs from cat_ranges to cat_file (#2044)
|
| 420 |
+
- Don't parse refFS templates by default (#2039, 2029)
|
| 421 |
+
- fix s3fs ci (#2035)
|
| 422 |
+
- fix: pass on_error when mv calls copy (#2030)
|
| 423 |
+
|
| 424 |
+
2026.4.0
|
| 425 |
+
--------
|
| 426 |
+
|
| 427 |
+
Fixes
|
| 428 |
+
|
| 429 |
+
- proper install in ci to grab versions (#2025)
|
| 430 |
+
- encode URLs in HTTP pipe_file (#2023)
|
| 431 |
+
- implement delete and write_test for dirFS (#2022)
|
| 432 |
+
- allow multiple local protocols (#2014)
|
| 433 |
+
- context closing for tar and zip (#2012)
|
| 434 |
+
- fix cat_file and cat_ranges for WholeFileCache (#2010)
|
| 435 |
+
|
| 436 |
+
Other
|
| 437 |
+
|
| 438 |
+
- usage warning to HTTP FS (#2024)
|
| 439 |
+
- update adl: message following retirement (#2019)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
2026.3.0
|
| 443 |
+
--------
|
| 444 |
+
|
| 445 |
+
Fixes
|
| 446 |
+
|
| 447 |
+
- non-string types in individual cond kwarg value env-vars (#2004)
|
| 448 |
+
- allow withdirs in glob (#1998)
|
| 449 |
+
- multi-file put in sftp (#1991)
|
| 450 |
+
|
| 451 |
+
2026.2.0
|
| 452 |
+
--------
|
| 453 |
+
|
| 454 |
+
Enhancements
|
| 455 |
+
|
| 456 |
+
- support append and update mode for cachedFSs (#1980)
|
| 457 |
+
- implement created()/modified() for webHDFS (#1971)
|
| 458 |
+
|
| 459 |
+
Fixes
|
| 460 |
+
|
| 461 |
+
- recover support for old zstandard package (#1987)
|
| 462 |
+
- remove prefetching loop in block-cache causing double read (#1984)
|
| 463 |
+
- fixes to parquet and known-cache (#1982, 1988, 1979)
|
| 464 |
+
- return None for streamed arrow file size (#1981)
|
| 465 |
+
- correct find() for ZipFS (#1976)
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
2026.1.0
|
| 469 |
+
--------
|
| 470 |
+
|
| 471 |
+
Put limits on install extras for s3fs/gcsfs to prevent installing
|
| 472 |
+
ancient versions via pip.
|
| 473 |
+
|
| 474 |
+
Enhancements
|
| 475 |
+
|
| 476 |
+
- configure TLS protocol version for FTP (#1958)
|
| 477 |
+
|
| 478 |
+
Fixes
|
| 479 |
+
|
| 480 |
+
- Respect auto_mkdir in mv for local (#1957)
|
| 481 |
+
|
| 482 |
+
Other
|
| 483 |
+
|
| 484 |
+
- link to pydantic, code and union implementations ($1956)
|
| 485 |
+
- use backport.zstd or builtin (#1962)
|
| 486 |
+
- docs typo (#1963)
|
| 487 |
+
|
| 488 |
+
2025.12.0
|
| 489 |
+
---------
|
| 490 |
+
|
| 491 |
+
Enhancements
|
| 492 |
+
|
| 493 |
+
- fsspec.parquet to support filters and multiple files (#1945)
|
| 494 |
+
|
| 495 |
+
Fixes
|
| 496 |
+
|
| 497 |
+
- passing withdirs in aync _glob() (#1953)
|
| 498 |
+
- fix _rm_file/_rm redirection in async (#1951)
|
| 499 |
+
- allow arrowFile to be seekable (#1950)
|
| 500 |
+
- add size attribute to arrowFile (#1944)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
Other
|
| 504 |
+
|
| 505 |
+
- support py3.14 and drop 3.9 (#1946)
|
| 506 |
+
- avoid ruff warning (#1942)
|
| 507 |
+
|
| 508 |
+
2025.10.0
|
| 509 |
+
---------
|
| 510 |
+
|
| 511 |
+
Enhancements
|
| 512 |
+
|
| 513 |
+
- specify storage_options not use use for tokenising; test instance cache (#1933)
|
| 514 |
+
- base class "chained" for FSs that pass through operations (#1929)
|
| 515 |
+
|
| 516 |
+
Fixes
|
| 517 |
+
|
| 518 |
+
- strip protocol for sftp (#1940)
|
| 519 |
+
- use one-step mv in jupyterfs (#1937)
|
| 520 |
+
- raise errors in jupyterfs, not return (#1936)
|
| 521 |
+
- add protocol attribute to http(#1935)
|
| 522 |
+
- allow ls() on a single file for arrowFS (#1931)
|
| 523 |
+
- support kwargs in webhdfs ls() (#1928)
|
| 524 |
+
- better discrimination for parquet in referenceFS (#1923)
|
| 525 |
+
- accept all mode= types in memoryFS (#1922)
|
| 526 |
+
- pass path list to put() in localtempfile for efficiency (#1920)
|
| 527 |
+
- fix docs errors (#1917)
|
| 528 |
+
|
| 529 |
+
Other
|
| 530 |
+
|
| 531 |
+
- add CoC (#1924)
|
| 532 |
+
- restrict github/gist tests because of rate limiting (#1918)
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
2025.9.0
|
| 536 |
+
--------
|
| 537 |
+
|
| 538 |
+
Enhancements
|
| 539 |
+
|
| 540 |
+
- include Last_modified info from HTTP headers to info (#1909)
|
| 541 |
+
- add optional semaphore to async-wrapper (#1908)
|
| 542 |
+
|
| 543 |
+
Fixes
|
| 544 |
+
|
| 545 |
+
- ensure cachingFSs show correct protocol (#1897)
|
| 546 |
+
- fix simplecache cat_ranges (#1892)
|
| 547 |
+
|
| 548 |
+
Other
|
| 549 |
+
|
| 550 |
+
- Style (#1894)
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
2025.7.0
|
| 554 |
+
--------
|
| 555 |
+
|
| 556 |
+
Enhancements
|
| 557 |
+
|
| 558 |
+
- only download HTML mime for http listing (#1889)
|
| 559 |
+
- add tos:// to registry (#1878)
|
| 560 |
+
|
| 561 |
+
Fixes
|
| 562 |
+
|
| 563 |
+
- use st_birthtime in localFS, if available (#1883)
|
| 564 |
+
- allow cat_* in simplecache (#1881)
|
| 565 |
+
- remove deprecated asyncio use (#1862)
|
| 566 |
+
- create event loop if it doesn't exist (#1857)
|
| 567 |
+
|
| 568 |
+
Other
|
| 569 |
+
|
| 570 |
+
- remove references to py38 (#1888)
|
| 571 |
+
- ruff updates (#1887, 1864)
|
| 572 |
+
- github rate limits in CI (#1879, 1877)
|
| 573 |
+
- acknowledge Anaconda support (#1876)
|
| 574 |
+
- add obstore to known implementations (#1875)
|
| 575 |
+
- add Microsoft storage to known implementations (#1853)
|
| 576 |
+
- use builtins zstd for py3.14 (#1874)
|
| 577 |
+
- gdrivefs -> gdrive_fsspec (#1858)
|
| 578 |
+
- windows version in CI (#1855)
|
| 579 |
+
- error message typo (#1854)
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
2025.5.1
|
| 583 |
+
--------
|
| 584 |
+
|
| 585 |
+
Enhancements
|
| 586 |
+
|
| 587 |
+
- file system for GitHub gists (#1791)
|
| 588 |
+
|
| 589 |
+
Other
|
| 590 |
+
|
| 591 |
+
- doc fixes (#1847, 1848)
|
| 592 |
+
|
| 593 |
+
2025.5.0
|
| 594 |
+
--------
|
| 595 |
+
|
| 596 |
+
Enhancements
|
| 597 |
+
|
| 598 |
+
- add rm in github: (##1839)
|
| 599 |
+
- cachingFS performance, don't ls every time (#1833)
|
| 600 |
+
- pyscript: protocol and optional entrypoint (#1828)
|
| 601 |
+
|
| 602 |
+
Fixes
|
| 603 |
+
|
| 604 |
+
- improve cp in generic (#1835)
|
| 605 |
+
- fix ls in dbfs (#1834)
|
| 606 |
+
- fix parquet tests for pyarrow 20 (#1831)
|
| 607 |
+
- fix crosslink for local tempfile (#1829)
|
| 608 |
+
- keep permissions in local transaction (#1826)
|
| 609 |
+
- signature compatibility in local cp() (#1820)
|
| 610 |
+
|
| 611 |
+
Other
|
| 612 |
+
|
| 613 |
+
- add "gs" at mention of gcsfs in docs (#1840)
|
| 614 |
+
- lint style (#1837)
|
| 615 |
+
- glob docstring to reflect reality (#1825)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
2025.3.2
|
| 619 |
+
--------
|
| 620 |
+
|
| 621 |
+
- drop support for py3.8
|
| 622 |
+
|
| 623 |
+
2025.3.1
|
| 624 |
+
--------
|
| 625 |
+
|
| 626 |
+
Enhancements
|
| 627 |
+
|
| 628 |
+
- LFS support in github: (#1810)
|
| 629 |
+
|
| 630 |
+
Fixes
|
| 631 |
+
|
| 632 |
+
- json should be a method fo requests shim (#1814)
|
| 633 |
+
- don't raise if known_implementation has no given error string (#1804)
|
| 634 |
+
|
| 635 |
+
Other
|
| 636 |
+
|
| 637 |
+
- rename protocols for sync-http (#1810)
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
2025.3.0
|
| 641 |
+
--------
|
| 642 |
+
|
| 643 |
+
Enhancements
|
| 644 |
+
|
| 645 |
+
- add pipe_file to HTTP (#1799, 1801)
|
| 646 |
+
- add sync http for pyodide (#1177)
|
| 647 |
+
- ls performance for local and detail=False (#1789)
|
| 648 |
+
|
| 649 |
+
Fixes
|
| 650 |
+
|
| 651 |
+
- dir/info consistency in dirfs (#1798)
|
| 652 |
+
- referenceFS async consistency (#1794, 1795)
|
| 653 |
+
- CI (#1793)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
2025.2.0
|
| 657 |
+
--------
|
| 658 |
+
|
| 659 |
+
Enhancements
|
| 660 |
+
|
| 661 |
+
- add open() to referenceFS (#1778)
|
| 662 |
+
|
| 663 |
+
Fixes
|
| 664 |
+
|
| 665 |
+
- don't make async open() in async-wrapper (#1769)
|
| 666 |
+
- fix CI following dask-expr upstream change (#1781)
|
| 667 |
+
- cope with zarr3 "Buffer" objects in referenceFS (#1784)
|
| 668 |
+
|
| 669 |
+
Other
|
| 670 |
+
|
| 671 |
+
- use itemgetter in archiveFS (#1764)
|
| 672 |
+
- document that newline is included in readline(s) (#1770)
|
| 673 |
+
- format/spelling (#1774, 1779, 1780)
|
| 674 |
+
|
| 675 |
+
2024.12.0
|
| 676 |
+
---------
|
| 677 |
+
|
| 678 |
+
Enhancements
|
| 679 |
+
|
| 680 |
+
- "exclusive" mode for writing (#1762, 1756, 174+)
|
| 681 |
+
- "tree" text display of filesystem contents (#1750)
|
| 682 |
+
- async wrapper for sync FSs (#1745)
|
| 683 |
+
- new known implementation: tosfs (#1739)
|
| 684 |
+
- consilidate block fetch requests (#1733)
|
| 685 |
+
|
| 686 |
+
Fixes
|
| 687 |
+
|
| 688 |
+
- better webHDFS proxies (#
|
| 689 |
+
- syn FSs in referenceFS (#1755)
|
| 690 |
+
- don't serialize file caches (#1753)
|
| 691 |
+
- race condition in local ls() (#1744)
|
| 692 |
+
- missing/nan references in parquet (#1738)
|
| 693 |
+
- _un_chain kwargs (@1736)
|
| 694 |
+
- async _cat_file in referenceFS (#1734)
|
| 695 |
+
|
| 696 |
+
Other
|
| 697 |
+
|
| 698 |
+
- fallback implementation for _fetch_range (#1732)
|
| 699 |
+
|
| 700 |
+
2024.10.0
|
| 701 |
+
---------
|
| 702 |
+
|
| 703 |
+
Fixes
|
| 704 |
+
|
| 705 |
+
- Performance of memoryFS rm (#1725)
|
| 706 |
+
- Performance of git FS info (#1712)
|
| 707 |
+
- Avoid git hex for newer pygit (#1703)
|
| 708 |
+
- tests fix for zip (#1700, 1691)
|
| 709 |
+
- missing open_async for dirFS (#1698)
|
| 710 |
+
- handle pathlib in zip (#1689)
|
| 711 |
+
- skip tests needing kerchunk if not installed (#1689)
|
| 712 |
+
- allow repeated kwargs in unchain (#1673)
|
| 713 |
+
|
| 714 |
+
Other
|
| 715 |
+
|
| 716 |
+
- Code style (#1704, 1706)
|
| 717 |
+
- allow pyarrow in referenceFS parquet (#1692)
|
| 718 |
+
- don't hardcode test port for parallel runs (#1690)
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
2024.9.0
|
| 722 |
+
--------
|
| 723 |
+
|
| 724 |
+
Enhancements
|
| 725 |
+
|
| 726 |
+
- fewer stat calls in localFS (#1659)
|
| 727 |
+
- faster find in ZIP (#1664)
|
| 728 |
+
|
| 729 |
+
Fixes
|
| 730 |
+
|
| 731 |
+
- paths without "/" in dirFS (#1638)
|
| 732 |
+
- paths with "/" in FTS (#1643, 1644)
|
| 733 |
+
- ls in parquet-based nested reference sets, and append (#1645, 1657)
|
| 734 |
+
- exception handling for SMB (#1650)
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
Other
|
| 738 |
+
|
| 739 |
+
- style (#1640, 1641, 1660)
|
| 740 |
+
- docs: xrootd (#1646)
|
| 741 |
+
- CI back on miniconda (#1658)
|
| 742 |
+
|
| 743 |
+
2024.6.1
|
| 744 |
+
--------
|
| 745 |
+
|
| 746 |
+
Fixes
|
| 747 |
+
|
| 748 |
+
- fix appending to non-dict reference sets (#1634)
|
| 749 |
+
- don't let generic edit info dicts (#1633)
|
| 750 |
+
- set https's loop before calling super (#1633)
|
| 751 |
+
- cached write file doesn't need to update it's size on close (#1633)
|
| 752 |
+
- fix JSON serialize for FSs with interior FSs (#1628, 1627)
|
| 753 |
+
- option to strip "password" when pickling (#1625)
|
| 754 |
+
- fix filecache write (#1622)
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
2024.6.0
|
| 758 |
+
--------
|
| 759 |
+
|
| 760 |
+
Enhancements
|
| 761 |
+
|
| 762 |
+
- allow dicts (not just bytes) for referenceFS (#1616
|
| 763 |
+
- make filesystems JSON serializeable (#1612)
|
| 764 |
+
- implement multifile cat() for github (#1620)
|
| 765 |
+
|
| 766 |
+
Fixes
|
| 767 |
+
|
| 768 |
+
- implement auto_mkdir for SMB (#1604)
|
| 769 |
+
|
| 770 |
+
Other
|
| 771 |
+
|
| 772 |
+
- add doc deps to pyproject (#1613)
|
| 773 |
+
- re-remove test from package (#1611)
|
| 774 |
+
- formatting (#1610, 1608, 1602)
|
| 775 |
+
- change monthly download badge (#1607)
|
| 776 |
+
|
| 777 |
+
2024.5.0
|
| 778 |
+
--------
|
| 779 |
+
|
| 780 |
+
Enhancements
|
| 781 |
+
|
| 782 |
+
- log hits/misses in bytes cachers (#1566)
|
| 783 |
+
|
| 784 |
+
Fixes
|
| 785 |
+
|
| 786 |
+
- SMB flaky tests (#1597)
|
| 787 |
+
- rsync: only delete files if there are some to delete (#1596)
|
| 788 |
+
- don't let files equal bytes objects (#1594)
|
| 789 |
+
- url_to_fs to stringify paths (#1591)
|
| 790 |
+
- assert types in MemoryFS (#1574)
|
| 791 |
+
- restore _strip_protocol signature for local (#1567)
|
| 792 |
+
- convert list to set when loading cache metadata (#1556)
|
| 793 |
+
|
| 794 |
+
Other
|
| 795 |
+
|
| 796 |
+
- remove mv_file (#1585)
|
| 797 |
+
- mv() should not swallow errors (#1576)
|
| 798 |
+
- change versioning template, allows easier co-install of dev s3fs (#1569)
|
| 799 |
+
- in ls_from_cache, avoid dounble lookup (#1561)
|
| 800 |
+
- expand=True in open() (#1558)
|
| 801 |
+
- build system to hatch (#1553)
|
| 802 |
+
|
| 803 |
+
2024.3.1
|
| 804 |
+
--------
|
| 805 |
+
|
| 806 |
+
Fixes
|
| 807 |
+
|
| 808 |
+
- allow override of expand in open() (#1549)
|
| 809 |
+
- root handling in local file paths, fix for windows (#1477)
|
| 810 |
+
|
| 811 |
+
2024.3.0
|
| 812 |
+
--------
|
| 813 |
+
|
| 814 |
+
Enhancements
|
| 815 |
+
|
| 816 |
+
- coroutines throttle to stream pool rather than batches (#1544)
|
| 817 |
+
- write transactions in simplecache (#1531)
|
| 818 |
+
- allow deep nested refs in referenceFS/parquet (#1530)
|
| 819 |
+
|
| 820 |
+
Fixes
|
| 821 |
+
|
| 822 |
+
- Fixes bug (#1476) that made open_files ignore expand=False (#1536)
|
| 823 |
+
- remove extra calling mapper contains (#1546)
|
| 824 |
+
- connection retry for SMB (#1533)
|
| 825 |
+
- zip64 should be on is allowZip64 is (#1532)
|
| 826 |
+
|
| 827 |
+
Other
|
| 828 |
+
|
| 829 |
+
- HTTP logging (#1547)
|
| 830 |
+
- url_to_fs exposed in package root (#1540)
|
| 831 |
+
- sort known_implementations (#1549)
|
| 832 |
+
- code quality/stype (#1538, 1537, 1528, 1526)
|
| 833 |
+
|
| 834 |
+
2024.2.0
|
| 835 |
+
--------
|
| 836 |
+
|
| 837 |
+
Enhancements
|
| 838 |
+
|
| 839 |
+
- add 9P known implementation (#1513)
|
| 840 |
+
- allow TqdmCallback subclassing (#1497, 1480)
|
| 841 |
+
- callbacks/branching kwargs handling and scopes (#1496, 1495, 1460)
|
| 842 |
+
- add aluuxioFS to known implementations (#1469)
|
| 843 |
+
- implement pipe_file for dirFS (#1465)
|
| 844 |
+
|
| 845 |
+
Fixes
|
| 846 |
+
|
| 847 |
+
- infer compression for .lzma files (#1514)
|
| 848 |
+
- fix append to categorical/parquet references (#1510)
|
| 849 |
+
- allow for FTP servers that list with leading "total" line (#1503)
|
| 850 |
+
- convert FTP failure to FileNotFound (#1494)
|
| 851 |
+
- out of order reference fix (#1492)
|
| 852 |
+
- retry "backoff" response for DBFS (#1491)
|
| 853 |
+
- referenceFS case for scalar arrays (#1487)
|
| 854 |
+
- fix create_parents for SFTP (#1484)
|
| 855 |
+
- fix local .ls() on files (#1479)
|
| 856 |
+
- allow Path and similar in _expand_path (#1475)
|
| 857 |
+
- make lazy references editable (#1468)
|
| 858 |
+
- fix eq for abstract buffered files (#1466)
|
| 859 |
+
- fit tqdm cleanup (#1463)
|
| 860 |
+
- fix passing kwargs from cached file to underlying FS (#1462)
|
| 861 |
+
|
| 862 |
+
Other
|
| 863 |
+
|
| 864 |
+
- fix tests for supports_empty_directories=False (#1512)
|
| 865 |
+
- don't read references in init for referenceFS (#1521)
|
| 866 |
+
- code cleaning (#1518, 1502, 1499, 1493, 1481)
|
| 867 |
+
- pass through "replication" for HDFS (#1486)
|
| 868 |
+
- record more info for HTTP info() (#1483)
|
| 869 |
+
- add timeout argument to githubFS (#1473)
|
| 870 |
+
- add more security pars to webHDFS (#1472)
|
| 871 |
+
|
| 872 |
+
2023.12.2
|
| 873 |
+
---------
|
| 874 |
+
|
| 875 |
+
Fixes
|
| 876 |
+
|
| 877 |
+
- top-level glob in ZIP (#1454)
|
| 878 |
+
- append mode on local ZIP files/truncate (#1449)
|
| 879 |
+
- restrict ":" as protocol marker to data: (#1452)
|
| 880 |
+
- sftp relative paths (#1451)
|
| 881 |
+
- http encoding in HTTP FS put_file (#1450)
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
2023.12.1
|
| 885 |
+
---------
|
| 886 |
+
|
| 887 |
+
Fixes
|
| 888 |
+
|
| 889 |
+
- Remove trailing "/" from directory names in zipFS/archive (#1445)
|
| 890 |
+
|
| 891 |
+
2023.12.0
|
| 892 |
+
---------
|
| 893 |
+
|
| 894 |
+
Enhancements
|
| 895 |
+
|
| 896 |
+
- allow HTTP size guess in more circumstances (#1440)
|
| 897 |
+
- allow kwargs passed to GUI to be dict (#1437)
|
| 898 |
+
- transaction support for writing via a cache FS (#1434)
|
| 899 |
+
- make cached FSs work better with async backends (#1429)
|
| 900 |
+
- allow FSs to set their transaction implementation (#1424)
|
| 901 |
+
- add dataFS (#1421, 1415)
|
| 902 |
+
- allow basic auth in webHDFS (#1409)
|
| 903 |
+
|
| 904 |
+
Fixes
|
| 905 |
+
|
| 906 |
+
- in referenceFS, maintain order when some keys are omitted in cat (#1436)
|
| 907 |
+
- nested subdirectory listing in referenceFS (#1433)
|
| 908 |
+
- allow "=" in webHDF paths (#1428)
|
| 909 |
+
- fix file mode to consistent "r+b" format (#1426)
|
| 910 |
+
- pass on kwargs in HTTP glob (#1422)
|
| 911 |
+
- allow Path in can_be_local and open_local (#1419, #1418)
|
| 912 |
+
- fix parent for cachedFS (#1413)
|
| 913 |
+
- "ends" list in _cat_ranges was incorrect (#1402)
|
| 914 |
+
|
| 915 |
+
Other
|
| 916 |
+
|
| 917 |
+
- smarter handling of exceptions when doing auto_mkdir (#1406)
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
2023.10.0
|
| 921 |
+
---------
|
| 922 |
+
|
| 923 |
+
Enhancements
|
| 924 |
+
|
| 925 |
+
- alias "local://" to "file://" (#1381)
|
| 926 |
+
- get size of file cache (#1377)
|
| 927 |
+
|
| 928 |
+
Fixes
|
| 929 |
+
|
| 930 |
+
- stop unexpected kwargs for SMB (#1391)
|
| 931 |
+
- dos formatting (#1383)
|
| 932 |
+
|
| 933 |
+
Other
|
| 934 |
+
|
| 935 |
+
- small optimisations in referenceFS (#1393)
|
| 936 |
+
- define ordering behaviour for entrypoints (#1389)
|
| 937 |
+
- style (#1387, 1386, 1385)
|
| 938 |
+
- add LazyReferenceMapper to API docs (#1378)
|
| 939 |
+
- add PyPI badge to README (#1376)
|
| 940 |
+
|
| 941 |
+
2023.9.2
|
| 942 |
+
--------
|
| 943 |
+
|
| 944 |
+
Fixes
|
| 945 |
+
|
| 946 |
+
- revert #1358: auto_mkdir in open() (#1365)
|
| 947 |
+
|
| 948 |
+
Other
|
| 949 |
+
|
| 950 |
+
- code style updates (#1373, 1372, 1371, 1370, 1369, 1364)
|
| 951 |
+
- update CI setup (#1386)
|
| 952 |
+
|
| 953 |
+
2023.9.1
|
| 954 |
+
--------
|
| 955 |
+
|
| 956 |
+
Enhancements
|
| 957 |
+
|
| 958 |
+
- #1353, save file cache metadata in JSON
|
| 959 |
+
- #1352, remove some unnecessary list iterations
|
| 960 |
+
|
| 961 |
+
Fixes
|
| 962 |
+
|
| 963 |
+
- #1361, re-allow None for default port for SMB
|
| 964 |
+
- #1360, initialising GUI widget FS with kwargs
|
| 965 |
+
- #1358, pass auto_mkdir vi url_to_fs again
|
| 966 |
+
|
| 967 |
+
Other
|
| 968 |
+
|
| 969 |
+
- #1354, auto delete temp cache directory
|
| 970 |
+
|
| 971 |
+
2023.9.0
|
| 972 |
+
--------
|
| 973 |
+
|
| 974 |
+
Enhancements
|
| 975 |
+
|
| 976 |
+
- #1346, add ocilake protocol
|
| 977 |
+
- #1345, implement async-sync and async-async generic cp and rsync
|
| 978 |
+
- #1344, add lakefs protocol
|
| 979 |
+
- #1337 add goatcounter to docs
|
| 980 |
+
- #1323, 1328, add xethub protocol
|
| 981 |
+
- #1320, in HTTP, check content-encoding when getting length
|
| 982 |
+
- #1303, add on_error in walk
|
| 983 |
+
- #1302, add dirfs attribute to mappers
|
| 984 |
+
- #1293, configure port for smb
|
| 985 |
+
|
| 986 |
+
Fixes
|
| 987 |
+
|
| 988 |
+
- #1349, don't reorder paths in bulk ops if source and dest are both lists
|
| 989 |
+
- #1333, allow mode="x" in get_fs_token_paths
|
| 990 |
+
- #1324, allow generic to work with complex URLs
|
| 991 |
+
- #1316, exclude bytes-cache kwargs in url_to_fs
|
| 992 |
+
- #1314, remote utcnow/utcfromtimestamp
|
| 993 |
+
- #1311, dirFS's protocol
|
| 994 |
+
- #1305, use get_file rather than get in file caching
|
| 995 |
+
- #1295, allow bz2 to be optional
|
| 996 |
+
|
| 997 |
+
Other
|
| 998 |
+
|
| 999 |
+
- #1340, 1339, 1329 more bulk ops testing
|
| 1000 |
+
- #1326, 1296 separate out classes in file caching for future enhancements
|
| 1001 |
+
|
| 1002 |
+
2023.6.0
|
| 1003 |
+
--------
|
| 1004 |
+
|
| 1005 |
+
Enhancements
|
| 1006 |
+
|
| 1007 |
+
- #1259, add maxdepth fo cp/get/put
|
| 1008 |
+
- #1263, allow dir modification during walk()
|
| 1009 |
+
- #1264, add boxfs to registry
|
| 1010 |
+
- #1266, optimise referenceFS lazy lookups, especially for writing parquet
|
| 1011 |
+
- #1287, 1288 "encoding" for FTP
|
| 1012 |
+
|
| 1013 |
+
Fixes
|
| 1014 |
+
|
| 1015 |
+
- #1273, (re)allow reading .zstd reference sets
|
| 1016 |
+
- #1275, resource.error for win32
|
| 1017 |
+
- #1278, range reads in dbfs
|
| 1018 |
+
- #1282, create parent directories in get_file
|
| 1019 |
+
- #1283, off-by-one in reference block writing
|
| 1020 |
+
- #1286, strip protocol in local rm_file
|
| 1021 |
+
|
| 1022 |
+
Other
|
| 1023 |
+
|
| 1024 |
+
- #1267, async bulk tests
|
| 1025 |
+
- #1268, types and mypy
|
| 1026 |
+
- #1277, 1279, drop outdated forms io.open, IOError
|
| 1027 |
+
|
| 1028 |
+
2023.5.0
|
| 1029 |
+
--------
|
| 1030 |
+
|
| 1031 |
+
Enhancements
|
| 1032 |
+
|
| 1033 |
+
- #1236, allow writing ReferenceFS references directly to parquet
|
| 1034 |
+
|
| 1035 |
+
Fixes
|
| 1036 |
+
|
| 1037 |
+
- #1255, copy of glob to single output directory
|
| 1038 |
+
- #1254, non-recursive copy of directory (no-op)
|
| 1039 |
+
- #1253, cleanup fix on close of ZIP FS
|
| 1040 |
+
- #1250, ignore dirs when copying list of files
|
| 1041 |
+
- #1249, don't error on register without clobber is registering same thing again
|
| 1042 |
+
- #1245, special case for other_files and relative path
|
| 1043 |
+
|
| 1044 |
+
Other
|
| 1045 |
+
|
| 1046 |
+
- #1248, add test harness into released wheel package
|
| 1047 |
+
- #1247, docs and tests around common bulk file operations
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
2023.4.0
|
| 1051 |
+
--------
|
| 1052 |
+
|
| 1053 |
+
Enhancements
|
| 1054 |
+
|
| 1055 |
+
- #1225, comprehensive docs of expected behaviour of cp/get/put and tests
|
| 1056 |
+
- #1216, test harness for any backend
|
| 1057 |
+
|
| 1058 |
+
Fixes
|
| 1059 |
+
|
| 1060 |
+
- #1224, small fixes in reference and dask FSs
|
| 1061 |
+
- #1218, mv is no-op when origin and destination are the same
|
| 1062 |
+
- #1217, await in AbstractStreamedFile
|
| 1063 |
+
- #1215, docbuild fixes
|
| 1064 |
+
- #1214, unneeded maxdepth manipulation in expand_path
|
| 1065 |
+
- #1213, pyarros and posixpath related test fixes
|
| 1066 |
+
- #1211, BackgroundBlockCache: keep a block longer if not yet used
|
| 1067 |
+
- #1210, webHDFS: location parameter
|
| 1068 |
+
|
| 1069 |
+
Other
|
| 1070 |
+
|
| 1071 |
+
- #1241, add HfFileSystem to registry
|
| 1072 |
+
- #1237, register_implementation clobber default changes to False
|
| 1073 |
+
- #1228, "full" and "devel" installation options
|
| 1074 |
+
- #1227, register_cache and reporting collision
|
| 1075 |
+
- #1221, docs about implementations and protocols
|
| 1076 |
+
|
| 1077 |
+
2023.3.0
|
| 1078 |
+
--------
|
| 1079 |
+
|
| 1080 |
+
Enhancements
|
| 1081 |
+
|
| 1082 |
+
- #1201, add directory FS to the registry and constructable from URLs
|
| 1083 |
+
- #1194, allow JSON for setting dict-like kwargs in the config
|
| 1084 |
+
- #1181, give arrow FS proper place in the registry
|
| 1085 |
+
- #1178, add experimental background-thread buffering cache
|
| 1086 |
+
- #1162, make ZipFS writable
|
| 1087 |
+
|
| 1088 |
+
Fixes
|
| 1089 |
+
|
| 1090 |
+
- #1202, fix on_error="omit" when using caching's cat
|
| 1091 |
+
- #1199, 1163, get/put/cp consistency and empty directories
|
| 1092 |
+
- #1197, 1183 use bytes for setting value on mapper using numpy
|
| 1093 |
+
- #1191, clean up open files in spec get_file
|
| 1094 |
+
- #1164, pass on kwargs correctly to http
|
| 1095 |
+
|
| 1096 |
+
Other
|
| 1097 |
+
|
| 1098 |
+
- #1186, make seekable=True default for pyarrow files
|
| 1099 |
+
- #1184, 1185, set minimum python version to 3.8
|
| 1100 |
+
|
| 1101 |
+
2023.1.0
|
| 1102 |
+
--------
|
| 1103 |
+
|
| 1104 |
+
Enhancements
|
| 1105 |
+
|
| 1106 |
+
- experimental DFReferenceFileSystem (#1157, 1138)
|
| 1107 |
+
- pyarrow seeking (#1154)
|
| 1108 |
+
- tar thread safety (#1132)
|
| 1109 |
+
- fsid method (#1122)
|
| 1110 |
+
|
| 1111 |
+
Fixes
|
| 1112 |
+
|
| 1113 |
+
- ReferenceFS order fix (#1158)
|
| 1114 |
+
- fix du and maxdepth (#1128, 1151)
|
| 1115 |
+
- http ranges (#1141)
|
| 1116 |
+
|
| 1117 |
+
Other
|
| 1118 |
+
|
| 1119 |
+
- coverage on referenceFS (#1133, 1123)
|
| 1120 |
+
- docs (#1152, 1150
|
| 1121 |
+
- remove code duplication in unchain (#1143, 1156, 1121)
|
| 1122 |
+
|
| 1123 |
+
2022.11.0
|
| 1124 |
+
---------
|
| 1125 |
+
|
| 1126 |
+
Enhancements
|
| 1127 |
+
|
| 1128 |
+
- Speed up FSMap._key_to_str (#1101)
|
| 1129 |
+
- Add modified/created to Memory and Arrow (#1096)
|
| 1130 |
+
- Clear expired cache method (#1092)
|
| 1131 |
+
- Allow seekable arrow file (#1091)
|
| 1132 |
+
- Allow append for arrow (#1089)
|
| 1133 |
+
- recursive for sftp.get (#1082)
|
| 1134 |
+
- topdown arg to walk() (#1081)
|
| 1135 |
+
|
| 1136 |
+
Fixes
|
| 1137 |
+
|
| 1138 |
+
- fix doc warnings (#1106, #1084)
|
| 1139 |
+
- Fix HDFS _strip_protocol (#1103)
|
| 1140 |
+
- Allow URLs with protocol for HDFS (#1099)
|
| 1141 |
+
- yarl in doc deps (#1095)
|
| 1142 |
+
- missing await in genericFS.cp (#1094)
|
| 1143 |
+
- explicit IPv4 for test HTTP server (#1088)
|
| 1144 |
+
- sort when merging ranges for referenceFS (#1087)
|
| 1145 |
+
|
| 1146 |
+
Other
|
| 1147 |
+
|
| 1148 |
+
- Check that snappy is snappy (#1079)
|
| 1149 |
+
|
| 1150 |
+
2022.10.0
|
| 1151 |
+
---------
|
| 1152 |
+
|
| 1153 |
+
Enhancements
|
| 1154 |
+
|
| 1155 |
+
- referenceFS consolidates reads in the same remote file (#1063)
|
| 1156 |
+
- localfs: add link/symlink/islink (#1059)
|
| 1157 |
+
- asyncfs: make mirroring methods optional (#1054)
|
| 1158 |
+
- local: info: provide st_ino and st_nlink from stat (#1053)
|
| 1159 |
+
- arrow_hdfs replaces hdfs (#1051)
|
| 1160 |
+
- Add read/write_text (#1047)
|
| 1161 |
+
- Add pipe/cat to genericFS (#1038)
|
| 1162 |
+
|
| 1163 |
+
Fixes
|
| 1164 |
+
|
| 1165 |
+
- SSH write doesn't return number of bytes (#1072)
|
| 1166 |
+
- wrap flush method for LocalFileOpened (#1070)
|
| 1167 |
+
- localfs: fix support for pathlib/os.PathLike objects in rm (#1058)
|
| 1168 |
+
- don't get_file remote FTP directory (#1056)
|
| 1169 |
+
- fix zip write to remote (#1046)
|
| 1170 |
+
- fix zip del following failed init (#1040)
|
| 1171 |
+
|
| 1172 |
+
Other
|
| 1173 |
+
|
| 1174 |
+
- add asynclocalfs to the registry (#1060)
|
| 1175 |
+
- add DVCFileSystem to the registry (#1049)
|
| 1176 |
+
- add downstream tests (#1037)
|
| 1177 |
+
- Don't auto-close OpenFiles (#1035)
|
| 1178 |
+
|
| 1179 |
+
2022.8.2
|
| 1180 |
+
--------
|
| 1181 |
+
|
| 1182 |
+
- don't close OpenFile on del (#1035)
|
| 1183 |
+
|
| 1184 |
+
2022.8.1
|
| 1185 |
+
--------
|
| 1186 |
+
|
| 1187 |
+
- revert #1024 (#1029), with strciter requirements on OpenFile usage
|
| 1188 |
+
|
| 1189 |
+
2022.8.0
|
| 1190 |
+
--------
|
| 1191 |
+
|
| 1192 |
+
Enhancements
|
| 1193 |
+
|
| 1194 |
+
- writable ZipFileSystem (#1017)
|
| 1195 |
+
- make OpenFile behave like files and remove dynamic closer in .open() (#1024)
|
| 1196 |
+
- use isal gunzip (#1008)
|
| 1197 |
+
|
| 1198 |
+
Fixes
|
| 1199 |
+
|
| 1200 |
+
- remove strip from _parent (#1022)
|
| 1201 |
+
- disallow aiohttp prereleases (#1018)
|
| 1202 |
+
- be sure to close cached file (#1016)
|
| 1203 |
+
- async rm in reverse order (#1014)
|
| 1204 |
+
- expose fileno in LocalFileOpener (#1010, #1005)
|
| 1205 |
+
- remove temp files with simplecache writing (#1006)
|
| 1206 |
+
- azure paths (#1003)
|
| 1207 |
+
- copy dircache keys before iter
|
| 1208 |
+
|
| 1209 |
+
|
| 1210 |
+
2022.7.1
|
| 1211 |
+
--------
|
| 1212 |
+
|
| 1213 |
+
Fixes
|
| 1214 |
+
|
| 1215 |
+
- Remove fspath from LocalFileOpener (#1005)
|
| 1216 |
+
- Revert 988 (#1003)
|
| 1217 |
+
|
| 1218 |
+
2022.7.0
|
| 1219 |
+
--------
|
| 1220 |
+
|
| 1221 |
+
Enhancements
|
| 1222 |
+
|
| 1223 |
+
- added fsspec-xrootd implementation to registry (#1000)
|
| 1224 |
+
- memory file not to copy bytes (#999)
|
| 1225 |
+
- Filie details passed to FUSE (#972)
|
| 1226 |
+
|
| 1227 |
+
Fixes
|
| 1228 |
+
|
| 1229 |
+
- Return info for root path of archives (#996)
|
| 1230 |
+
- arbitrary kwargs passed through in pipe_file (#993)
|
| 1231 |
+
- special cases for host in URLs for azure (#988)
|
| 1232 |
+
- unstrip protocol criterion (#980)
|
| 1233 |
+
- HTTPFile serialisation (#973)
|
| 1234 |
+
|
| 1235 |
+
Other
|
| 1236 |
+
|
| 1237 |
+
- Show erroring path in FileNotFounds (#989)
|
| 1238 |
+
- Reference file info without searching directory tree (#985)
|
| 1239 |
+
- Truncate for local files (#975)
|
| 1240 |
+
|
| 1241 |
+
|
| 1242 |
+
2022.5.0
|
| 1243 |
+
--------
|
| 1244 |
+
|
| 1245 |
+
Enhancements
|
| 1246 |
+
|
| 1247 |
+
- mutable ReferenceFS (#958)
|
| 1248 |
+
|
| 1249 |
+
Fixes
|
| 1250 |
+
|
| 1251 |
+
- Make archive FSs not cachable (#966)
|
| 1252 |
+
- glob fixes (#961)
|
| 1253 |
+
- generic copy with unknown size (#959)
|
| 1254 |
+
- zstd open (#956)
|
| 1255 |
+
- empty archive file (#954)
|
| 1256 |
+
- tar chaining (#950, 947)
|
| 1257 |
+
- missing exceptions in mapper (#940)
|
| 1258 |
+
|
| 1259 |
+
Other
|
| 1260 |
+
|
| 1261 |
+
- update registry (#852)
|
| 1262 |
+
- allow None cache (#942)
|
| 1263 |
+
- mappers to remember init arguments (#939)
|
| 1264 |
+
- cache docstrings (#933)
|
| 1265 |
+
|
| 1266 |
+
2022.03.0
|
| 1267 |
+
---------
|
| 1268 |
+
|
| 1269 |
+
Enhancements
|
| 1270 |
+
|
| 1271 |
+
- tqdm example callback with simple methods (#931, 902)
|
| 1272 |
+
- Allow empty root in get_mapper (#930)
|
| 1273 |
+
- implement real info for reference FS (#919)
|
| 1274 |
+
- list known implementations and compressions (#913)
|
| 1275 |
+
|
| 1276 |
+
Fixes
|
| 1277 |
+
|
| 1278 |
+
- git branch for testing git backend (#929)
|
| 1279 |
+
- maintain mem FS's root (#926)
|
| 1280 |
+
- kargs to FS in parquet module (#921)
|
| 1281 |
+
- fix on_error in references (#917)
|
| 1282 |
+
- tar ls consistency (#9114)
|
| 1283 |
+
- pyarrow: don't decompress twice (#911)
|
| 1284 |
+
- fix FUSE tests (#905)
|
| 1285 |
+
|
| 1286 |
+
|
| 1287 |
+
2022.02.0
|
| 1288 |
+
---------
|
| 1289 |
+
|
| 1290 |
+
Enhancements
|
| 1291 |
+
|
| 1292 |
+
- reference FS performance (#892, 900)
|
| 1293 |
+
- directory/prefix FS (#745)
|
| 1294 |
+
|
| 1295 |
+
Fixes
|
| 1296 |
+
|
| 1297 |
+
- FUSE (#905, 891)
|
| 1298 |
+
- iteration in threads (#893)
|
| 1299 |
+
- OpenFiles slicing (#887)
|
| 1300 |
+
|
| 1301 |
+
Other
|
| 1302 |
+
|
| 1303 |
+
- drop py36 (#889, 901)
|
| 1304 |
+
|
| 1305 |
+
2022.01.0
|
| 1306 |
+
---------
|
| 1307 |
+
|
| 1308 |
+
Fixes
|
| 1309 |
+
|
| 1310 |
+
- blocks cache metadata (#746)
|
| 1311 |
+
- default SMB port (#853)
|
| 1312 |
+
- caching fixes (#856, 855)
|
| 1313 |
+
- explicit close for http files (#866)
|
| 1314 |
+
- put_file to continue when no bytes (#869, 870)
|
| 1315 |
+
|
| 1316 |
+
Other
|
| 1317 |
+
|
| 1318 |
+
- temporary files location (#851, 871)
|
| 1319 |
+
- async abstract methods (#858, 859, 860)
|
| 1320 |
+
- md5 for FIPS (#872)
|
| 1321 |
+
- remove deprecated pyarrow/distutils (#880, 881)
|
| 1322 |
+
|
| 1323 |
+
2021.11.1
|
| 1324 |
+
---------
|
| 1325 |
+
|
| 1326 |
+
Enhancements
|
| 1327 |
+
|
| 1328 |
+
- allow compression for fs.open (#826)
|
| 1329 |
+
- batch more async operations (#824)
|
| 1330 |
+
- allow github backend for alternate URL (#815)
|
| 1331 |
+
- speec up reference filesystem (#811)
|
| 1332 |
+
|
| 1333 |
+
Fixes
|
| 1334 |
+
|
| 1335 |
+
- fixes for parquet functionality (#821, 817)
|
| 1336 |
+
- typos and docs (#839, 833, 816)
|
| 1337 |
+
- local root (#829)
|
| 1338 |
+
|
| 1339 |
+
Other
|
| 1340 |
+
|
| 1341 |
+
- remove BlockSizeError for http (#830)
|
| 1342 |
+
|
| 1343 |
+
2021.11.0
|
| 1344 |
+
---------
|
| 1345 |
+
|
| 1346 |
+
Enhancement
|
| 1347 |
+
|
| 1348 |
+
- parquet-specific module and cache type (#813, #806)
|
| 1349 |
+
|
| 1350 |
+
Fixes
|
| 1351 |
+
|
| 1352 |
+
- empty ranges (#802, 801, 803)
|
| 1353 |
+
- doc typos (#791, 808)
|
| 1354 |
+
- entrypoints processing (#784)
|
| 1355 |
+
- cat in ZIP (#789)
|
| 1356 |
+
|
| 1357 |
+
Other
|
| 1358 |
+
|
| 1359 |
+
- move to fsspec org
|
| 1360 |
+
- doc deps (#786, 791)
|
| 1361 |
+
|
| 1362 |
+
2021.10.1
|
| 1363 |
+
---------
|
| 1364 |
+
|
| 1365 |
+
Fixes
|
| 1366 |
+
|
| 1367 |
+
- Removed inaccurate ``ZipFileSystem.cat()`` override so that the base
|
| 1368 |
+
class' version is used (#789)
|
| 1369 |
+
- fix entrypoint processing (#784)
|
| 1370 |
+
- case where no blocks of a block-cache have yet been loaded (#801)
|
| 1371 |
+
- don't fetch empty ranges (#802, 803)
|
| 1372 |
+
|
| 1373 |
+
Other
|
| 1374 |
+
|
| 1375 |
+
- simplify doc deps (#786, 791)
|
| 1376 |
+
|
| 1377 |
+
|
| 1378 |
+
2021.10.0
|
| 1379 |
+
---------
|
| 1380 |
+
|
| 1381 |
+
Fixes
|
| 1382 |
+
|
| 1383 |
+
- only close http connector if present (#779)
|
| 1384 |
+
- hdfs strip protocol (#778)
|
| 1385 |
+
- fix filecache with check_files (#772)
|
| 1386 |
+
- put_file to use _parent (#771)
|
| 1387 |
+
|
| 1388 |
+
Other
|
| 1389 |
+
|
| 1390 |
+
- add kedro link (#781)
|
| 1391 |
+
|
| 1392 |
+
2021.09.0
|
| 1393 |
+
---------
|
| 1394 |
+
|
| 1395 |
+
Enhancement
|
| 1396 |
+
|
| 1397 |
+
- http put from file-like (#764)
|
| 1398 |
+
- implement webhdfs cp/rm_file (#762)
|
| 1399 |
+
- multiple (and concurrent) cat_ranges (#744)
|
| 1400 |
+
|
| 1401 |
+
Fixes
|
| 1402 |
+
|
| 1403 |
+
- sphinx warnings (#769)
|
| 1404 |
+
- lexists for links (#757)
|
| 1405 |
+
- update versioneer (#750)
|
| 1406 |
+
- hdfs updates (#749)
|
| 1407 |
+
- propagate async timeout error (#746)
|
| 1408 |
+
- fix local file seekable (#743)
|
| 1409 |
+
- fix http isdir when does not exist (#741)
|
| 1410 |
+
|
| 1411 |
+
Other
|
| 1412 |
+
|
| 1413 |
+
- ocifs, arrow added (#754, #765)
|
| 1414 |
+
- promote url_to_fs to top level (#753)
|
| 1415 |
+
|
| 1416 |
+
2021.08.1
|
| 1417 |
+
---------
|
| 1418 |
+
|
| 1419 |
+
Enhancements
|
| 1420 |
+
|
| 1421 |
+
- HTTP get_file/put_file APIs now support callbacks (#731)
|
| 1422 |
+
- New HTTP put_file method for transferring data to the remote server (chunked) (#731)
|
| 1423 |
+
- Customizable HTTP client initializers (through passing ``get_client`` argument) (#731, #701)
|
| 1424 |
+
- Support for various checksum / fingerprint headers in HTTP ``info()`` (#731)
|
| 1425 |
+
- local implementation of rm_file (#736)
|
| 1426 |
+
- local speed improvements (#711)
|
| 1427 |
+
- sharing options in SMB (#706)
|
| 1428 |
+
- streaming cat/get for ftp (#700)
|
| 1429 |
+
|
| 1430 |
+
Fixes
|
| 1431 |
+
|
| 1432 |
+
- check for remote directory when putting (#737)
|
| 1433 |
+
- storage_option update handling (#734(
|
| 1434 |
+
- await HTTP call before checking status (#726)
|
| 1435 |
+
- ftp connect (#722)
|
| 1436 |
+
- bytes conversion of times in mapper (#721)
|
| 1437 |
+
- variable overwrite in WholeFileCache cat (#719)
|
| 1438 |
+
- http file size again (#718)
|
| 1439 |
+
- rm and create directories in ftp (#716, #703)
|
| 1440 |
+
- list of files in async put (#713)
|
| 1441 |
+
- bytes to dict in cat (#710)
|
| 1442 |
+
|
| 1443 |
+
|
| 1444 |
+
2021.07.0
|
| 1445 |
+
---------
|
| 1446 |
+
|
| 1447 |
+
Enhancements
|
| 1448 |
+
|
| 1449 |
+
- callbacks (#697)
|
| 1450 |
+
|
| 1451 |
+
2021.06.1
|
| 1452 |
+
---------
|
| 1453 |
+
|
| 1454 |
+
Enhancements
|
| 1455 |
+
|
| 1456 |
+
- Introduce ``fsspec.asyn.fsspec_loop`` to temporarily switch to the fsspec loop. (#671)
|
| 1457 |
+
- support list for local rm (#678)
|
| 1458 |
+
|
| 1459 |
+
Fixes
|
| 1460 |
+
|
| 1461 |
+
- error when local mkdir twice (#679)
|
| 1462 |
+
- fix local info regression for pathlike (#667)
|
| 1463 |
+
|
| 1464 |
+
Other
|
| 1465 |
+
|
| 1466 |
+
- link to wandbfs (#664)
|
| 1467 |
+
|
| 1468 |
+
2021.06.0
|
| 1469 |
+
---------
|
| 1470 |
+
|
| 1471 |
+
Enhancements
|
| 1472 |
+
|
| 1473 |
+
- Better testing and folder handling for Memory (#654)
|
| 1474 |
+
- Negative indexes for cat_file (#653)
|
| 1475 |
+
- optimize local file listing (#647)
|
| 1476 |
+
|
| 1477 |
+
Fixes
|
| 1478 |
+
|
| 1479 |
+
- FileNoteFound in http and range exception subclass (#649, 646)
|
| 1480 |
+
- async timeouts (#643, 645)
|
| 1481 |
+
- stringify path for pyarrow legacy (#630)
|
| 1482 |
+
|
| 1483 |
+
|
| 1484 |
+
Other
|
| 1485 |
+
|
| 1486 |
+
- The ``fsspec.asyn.get_loop()`` will always return a loop of a selector policy (#658)
|
| 1487 |
+
- add helper to construct Range headers for cat_file (#655)
|
| 1488 |
+
|
| 1489 |
+
|
| 1490 |
+
2021.05.0
|
| 1491 |
+
---------
|
| 1492 |
+
|
| 1493 |
+
|
| 1494 |
+
Enhancements
|
| 1495 |
+
|
| 1496 |
+
- Enable listings cache for HTTP filesystem (#560)
|
| 1497 |
+
- Fold ZipFileSystem and LibArchiveFileSystem into a generic implementation and
|
| 1498 |
+
add new TarFileSystem (#561)
|
| 1499 |
+
- Use throttling for the ``get``/``put`` methods of ``AsyncFileSystem`` (#629)
|
| 1500 |
+
- rewrite for archive filesystems (#624)
|
| 1501 |
+
- HTTP listings caching (#623)
|
| 1502 |
+
|
| 1503 |
+
Fixes
|
| 1504 |
+
|
| 1505 |
+
- gcsfs tests (#638)
|
| 1506 |
+
- stringify_path for arrow (#630)
|
| 1507 |
+
|
| 1508 |
+
Other
|
| 1509 |
+
|
| 1510 |
+
- s3a:// alias
|
| 1511 |
+
|
| 1512 |
+
|
| 1513 |
+
2021.04.0
|
| 1514 |
+
---------
|
| 1515 |
+
|
| 1516 |
+
Major changes
|
| 1517 |
+
|
| 1518 |
+
- calendar versioning
|
| 1519 |
+
|
| 1520 |
+
Enhancements
|
| 1521 |
+
|
| 1522 |
+
- better link and size finding for HTTP (#610, %99)
|
| 1523 |
+
- link following in Local (#608)
|
| 1524 |
+
- ReferenceFileSystem dev (#606, #604, #602)
|
| 1525 |
+
|
| 1526 |
+
Fixes
|
| 1527 |
+
|
| 1528 |
+
- drop metadata dep (#605)
|
| 1529 |
+
|
| 1530 |
+
|
| 1531 |
+
0.9.0
|
| 1532 |
+
-----
|
| 1533 |
+
|
| 1534 |
+
Major Changes:
|
| 1535 |
+
|
| 1536 |
+
- avoid nested sync calls by copying code (#581, #586, docs #593)
|
| 1537 |
+
- release again for py36 (#564, #575)
|
| 1538 |
+
|
| 1539 |
+
Enhancements:
|
| 1540 |
+
|
| 1541 |
+
- logging in mmap cacher, explicitly close files (#559)
|
| 1542 |
+
- make LocalFileOpener an IOBase (#589)
|
| 1543 |
+
- better reference file system (#568, #582, #584, #585)
|
| 1544 |
+
- first-chunk cache (#580)
|
| 1545 |
+
- sftp listdir (#571)
|
| 1546 |
+
- http logging and fetch all (#551, #558)
|
| 1547 |
+
- doc: entry points (#548)
|
| 1548 |
+
|
| 1549 |
+
Fixes:
|
| 1550 |
+
|
| 1551 |
+
- get_mapper for caching filesystems (#559)
|
| 1552 |
+
- fix cross-device file move (#547)
|
| 1553 |
+
- store paths without trailing "/" for DBFS (#557)
|
| 1554 |
+
- errors that happen on ``_initiate_upload`` when closing the
|
| 1555 |
+
``AbstractBufferedFile`` will now be propagated (#587)
|
| 1556 |
+
- infer_compressions with upper case suffix ($595)
|
| 1557 |
+
- file initialiser errors (#587)
|
| 1558 |
+
- CI fix (#563)
|
| 1559 |
+
- local file commit cross-device (#547)
|
| 1560 |
+
|
| 1561 |
+
Version 0.8.7
|
| 1562 |
+
-------------
|
| 1563 |
+
|
| 1564 |
+
Fixes:
|
| 1565 |
+
|
| 1566 |
+
- fix error with pyarrow metadata for some pythons (#546)
|
| 1567 |
+
|
| 1568 |
+
Version 0.8.6
|
| 1569 |
+
-------------
|
| 1570 |
+
|
| 1571 |
+
Features:
|
| 1572 |
+
|
| 1573 |
+
- Add dbfs:// support (#504, #514)
|
| 1574 |
+
|
| 1575 |
+
Enhancements
|
| 1576 |
+
|
| 1577 |
+
- don't import pyarrow (#503)
|
| 1578 |
+
- update entry points syntax (#515)
|
| 1579 |
+
- ci precommit hooks (#534)
|
| 1580 |
+
|
| 1581 |
+
Fixes:
|
| 1582 |
+
|
| 1583 |
+
- random appending of a directory within the filesystems ``find()`` method (#507, 537)
|
| 1584 |
+
- fix git tests (#501)
|
| 1585 |
+
- fix recursive memfs operations (#502)
|
| 1586 |
+
- fix recursive/maxdepth for cp (#508)
|
| 1587 |
+
- fix listings cache timeout (#513)
|
| 1588 |
+
- big endian bytes tests (#519)
|
| 1589 |
+
- docs syntax (#535, 524, 520, 542)
|
| 1590 |
+
- transactions and reads (#533)
|
| 1591 |
+
|
| 1592 |
+
Version 0.8.5
|
| 1593 |
+
-------------
|
| 1594 |
+
|
| 1595 |
+
Features:
|
| 1596 |
+
|
| 1597 |
+
- config system
|
| 1598 |
+
- libarchive implementation
|
| 1599 |
+
- add reference file system implementation
|
| 1600 |
+
|
| 1601 |
+
Version 0.8.4
|
| 1602 |
+
-------------
|
| 1603 |
+
|
| 1604 |
+
Features:
|
| 1605 |
+
|
| 1606 |
+
- function ``can_be_local`` to see whether URL is compatible with ``open_local``
|
| 1607 |
+
- concurrent cat with filecaches, if backend supports it
|
| 1608 |
+
- jupyter FS
|
| 1609 |
+
|
| 1610 |
+
Fixes:
|
| 1611 |
+
|
| 1612 |
+
- dircache expiry after transaction
|
| 1613 |
+
- blockcache garbage collection
|
| 1614 |
+
- close for HDFS
|
| 1615 |
+
- windows tests
|
| 1616 |
+
- glob depth with "**"
|
| 1617 |
+
|
| 1618 |
+
Version 0.8.3
|
| 1619 |
+
-------------
|
| 1620 |
+
|
| 1621 |
+
Features:
|
| 1622 |
+
|
| 1623 |
+
- error options for cat
|
| 1624 |
+
- memory fs created time in detailed ``ls```
|
| 1625 |
+
|
| 1626 |
+
|
| 1627 |
+
Fixes:
|
| 1628 |
+
|
| 1629 |
+
- duplicate directories could appear in MemoryFileSystem
|
| 1630 |
+
- Added support for hat dollar lbrace rbrace regex character escapes in glob
|
| 1631 |
+
- Fix blockcache (was doing unnecessary work)
|
| 1632 |
+
- handle multibyte dtypes in readinto
|
| 1633 |
+
- Fix missing kwargs in call to _copy in asyn
|
| 1634 |
+
|
| 1635 |
+
Other:
|
| 1636 |
+
|
| 1637 |
+
- Stop inheriting from pyarrow.filesystem for pyarrow>=2.0
|
| 1638 |
+
- Raise low-level program friendly OSError.
|
| 1639 |
+
- Guard against instance reuse in new processes
|
| 1640 |
+
- Make hash_name a method on CachingFileSystem to make it easier to change.
|
| 1641 |
+
- Use get_event_loop for py3.6 compatibility
|
| 1642 |
+
|
| 1643 |
+
Version 0.8.2
|
| 1644 |
+
-------------
|
| 1645 |
+
|
| 1646 |
+
Fixes:
|
| 1647 |
+
|
| 1648 |
+
- More careful strip for caching
|
| 1649 |
+
|
| 1650 |
+
Version 0.8.1
|
| 1651 |
+
-------------
|
| 1652 |
+
|
| 1653 |
+
Features:
|
| 1654 |
+
|
| 1655 |
+
- add sign to base class
|
| 1656 |
+
- Allow calling of coroutines from normal code when running async
|
| 1657 |
+
- Implement writing for cached many files
|
| 1658 |
+
- Allow concurrent caching of remote files
|
| 1659 |
+
- Add gdrive:// protocol
|
| 1660 |
+
|
| 1661 |
+
Fixes:
|
| 1662 |
+
|
| 1663 |
+
- Fix memfs with exact ls
|
| 1664 |
+
- HTTPFileSystem requires requests and aiohttp in registry
|
| 1665 |
+
|
| 1666 |
+
Other:
|
| 1667 |
+
|
| 1668 |
+
- Allow http kwargs to clientSession
|
| 1669 |
+
- Use extras_require in setup.py for optional dependencies
|
| 1670 |
+
- Replacing md5 with sha256 for hash (CVE req)
|
| 1671 |
+
- Test against Python 3.8, drop 3.5 testing
|
| 1672 |
+
- add az alias for abfs
|
| 1673 |
+
|
| 1674 |
+
Version 0.8.0
|
| 1675 |
+
-------------
|
| 1676 |
+
|
| 1677 |
+
Major release allowing async implementations with concurrent batch
|
| 1678 |
+
operations.
|
| 1679 |
+
|
| 1680 |
+
Features:
|
| 1681 |
+
|
| 1682 |
+
- async filesystem spec, first applied to HTTP
|
| 1683 |
+
- OpenFiles cContext for multiple files
|
| 1684 |
+
- Document async, and ensure docstrings
|
| 1685 |
+
- Make LocalFileOpener iterable
|
| 1686 |
+
- handle smb:// protocol using smbprotocol package
|
| 1687 |
+
- allow Path object in open
|
| 1688 |
+
- simplecache write mode
|
| 1689 |
+
|
| 1690 |
+
Fixes:
|
| 1691 |
+
|
| 1692 |
+
- test_local: fix username not in home path
|
| 1693 |
+
- Tighten cacheFS if dir deleted
|
| 1694 |
+
- Fix race condition of lzma import when using threads
|
| 1695 |
+
- properly rewind MemoryFile
|
| 1696 |
+
- OpenFile newline in reduce
|
| 1697 |
+
|
| 1698 |
+
Other:
|
| 1699 |
+
|
| 1700 |
+
- Add aiobotocore to deps for s3fs check
|
| 1701 |
+
- Set default clobber=True on impl register
|
| 1702 |
+
- Use _get_kwargs_from_url when unchaining
|
| 1703 |
+
- Add cache_type and cache_options to HTTPFileSystem constructor
|
| 1704 |
+
|
| 1705 |
+
Version 0.7.5
|
| 1706 |
+
-------------
|
| 1707 |
+
|
| 1708 |
+
* async implemented for HTTP as prototype (read-only)
|
| 1709 |
+
* write for simplecache
|
| 1710 |
+
* added SMB (Samba, protocol >=2) implementation
|
| 1711 |
+
|
| 1712 |
+
Version 0.7.4
|
| 1713 |
+
-------------
|
| 1714 |
+
|
| 1715 |
+
* panel-based GUI
|
| 1716 |
+
|
| 1717 |
+
0.7.3 series
|
| 1718 |
+
------------
|
| 1719 |
+
|
| 1720 |
+
* added ``git`` and ``github`` interfaces
|
| 1721 |
+
* added chained syntax for open, open_files and get_mapper
|
| 1722 |
+
* adapt webHDFS for HttpFS
|
| 1723 |
+
* added open_local
|
| 1724 |
+
* added ``simplecache``, and compression to both file caches
|
| 1725 |
+
|
| 1726 |
+
|
| 1727 |
+
Version 0.6.2
|
| 1728 |
+
-------------
|
| 1729 |
+
|
| 1730 |
+
* Added ``adl`` and ``abfs`` protocols to the known implementations registry (:pr:`209`)
|
| 1731 |
+
* Fixed issue with whole-file caching and implementations providing multiple protocols (:pr:`219`)
|
| 1732 |
+
|
| 1733 |
+
Version 0.6.1
|
| 1734 |
+
-------------
|
| 1735 |
+
|
| 1736 |
+
* ``LocalFileSystem`` is now considered a filestore by pyarrow (:pr:`211`)
|
| 1737 |
+
* Fixed bug in HDFS filesystem with ``cache_options`` (:pr:`202`)
|
| 1738 |
+
* Fixed instance caching bug with multiple instances (:pr:`203`)
|
| 1739 |
+
|
| 1740 |
+
|
| 1741 |
+
Version 0.6.0
|
| 1742 |
+
-------------
|
| 1743 |
+
|
| 1744 |
+
* Fixed issues with filesystem instance caching. This was causing authorization errors
|
| 1745 |
+
in downstream libraries like ``gcsfs`` and ``s3fs`` in multi-threaded code (:pr:`155`, :pr:`181`)
|
| 1746 |
+
* Changed the default file caching strategy to :class:`fsspec.caching.ReadAheadCache` (:pr:`193`)
|
| 1747 |
+
* Moved file caches to the new ``fsspec.caching`` module. They're still available from
|
| 1748 |
+
their old location in ``fsspec.core``, but we recommend using the new location for new code (:pr:`195`)
|
| 1749 |
+
* Added a new file caching strategy, :class:`fsspec.caching.BlockCache` for fetching and caching
|
| 1750 |
+
file reads in blocks (:pr:`191`).
|
| 1751 |
+
* Fixed equality checks for file system instance to return ``False`` when compared to objects
|
| 1752 |
+
other than file systems (:pr:`192`)
|
| 1753 |
+
* Fixed a bug in ``fsspec.FSMap.keys`` returning a generator, which was consumed upon iteration (:pr:`189`).
|
| 1754 |
+
* Removed the magic addition of aliases in ``AbstractFileSystem.__init__``. Now alias methods are always
|
| 1755 |
+
present (:pr:`177`)
|
| 1756 |
+
* Deprecated passing ``trim`` to :class:`fsspec.spec.AbstractBufferedFile`. Pass it in ``storage_options`` instead (:pr:`188`)
|
| 1757 |
+
* Improved handling of requests for :class:`fsspec.implementations.http.HTTPFileSystem` when the
|
| 1758 |
+
HTTP server responds with an (incorrect) content-length of 0 (:pr:`163`)
|
| 1759 |
+
* Added a ``detail=True`` parameter to :meth:`fsspec.spec.AbstractFileSystem.ls` (:pr:`168`)
|
| 1760 |
+
* Fixed handling of UNC/DFS paths (:issue:`154`)
|
| 1761 |
+
|
| 1762 |
+
.. raw:: html
|
| 1763 |
+
|
| 1764 |
+
<script data-goatcounter="https://fsspec.goatcounter.com/count"
|
| 1765 |
+
async src="//gc.zgo.at/count.js"></script>
|
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/code-of-conduct.rst
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Code of Conduct
|
| 2 |
+
===============
|
| 3 |
+
|
| 4 |
+
All participants in the fsspec community are expected to adhere to a Code of Conduct.
|
| 5 |
+
|
| 6 |
+
As contributors and maintainers of this project, and in the interest of
|
| 7 |
+
fostering an open and welcoming community, we pledge to respect all people who
|
| 8 |
+
contribute through reporting issues, posting feature requests, updating
|
| 9 |
+
documentation, submitting pull requests or patches, and other activities.
|
| 10 |
+
|
| 11 |
+
We are committed to making participation in this project a harassment-free
|
| 12 |
+
experience for everyone, treating everyone as unique humans deserving of
|
| 13 |
+
respect.
|
| 14 |
+
|
| 15 |
+
Examples of unacceptable behaviour by participants include:
|
| 16 |
+
|
| 17 |
+
- The use of sexualized language or imagery
|
| 18 |
+
- Personal attacks
|
| 19 |
+
- Trolling or insulting/derogatory comments
|
| 20 |
+
- Public or private harassment
|
| 21 |
+
- Publishing other's private information, such as physical or electronic
|
| 22 |
+
addresses, without explicit permission
|
| 23 |
+
- Other unethical or unprofessional conduct
|
| 24 |
+
|
| 25 |
+
Project maintainers have the right and responsibility to remove, edit, or
|
| 26 |
+
reject comments, commits, code, wiki edits, issues, and other contributions
|
| 27 |
+
that are not aligned to this Code of Conduct, or to ban temporarily or
|
| 28 |
+
permanently any contributor for other behaviours that they deem inappropriate,
|
| 29 |
+
threatening, offensive, or harmful.
|
| 30 |
+
|
| 31 |
+
By adopting this Code of Conduct, project maintainers commit themselves
|
| 32 |
+
to fairly and consistently applying these principles to every aspect of
|
| 33 |
+
managing this project. Project maintainers who do not follow or enforce
|
| 34 |
+
the Code of Conduct may be permanently removed from the project team.
|
| 35 |
+
|
| 36 |
+
This code of conduct applies both within project spaces and in public
|
| 37 |
+
spaces when an individual is representing the project or its community.
|
| 38 |
+
|
| 39 |
+
If you feel the code of conduct has been violated, please report the
|
| 40 |
+
incident to the fsspec core team.
|
| 41 |
+
|
| 42 |
+
Reporting
|
| 43 |
+
---------
|
| 44 |
+
|
| 45 |
+
If you believe someone is violating theCode of Conduct we ask that you report it
|
| 46 |
+
to the Project by emailing community@anaconda.com. All reports will be kept
|
| 47 |
+
confidential. In some cases we may determine that a public statement will need
|
| 48 |
+
to be made. If that's the case, the identities of all victims and reporters
|
| 49 |
+
will remain confidential unless those individuals instruct us otherwise.
|
| 50 |
+
If you believe anyone is in physical danger, please notify appropriate law
|
| 51 |
+
enforcement first.
|
| 52 |
+
|
| 53 |
+
In your report please include:
|
| 54 |
+
|
| 55 |
+
- Your contact info
|
| 56 |
+
- Names (real, nicknames, or pseudonyms) of any individuals involved.
|
| 57 |
+
If there were other witnesses besides you, please try to include them as well.
|
| 58 |
+
- When and where the incident occurred. Please be as specific as possible.
|
| 59 |
+
- Your account of what occurred. If there is a publicly available record
|
| 60 |
+
please include a link.
|
| 61 |
+
- Any extra context you believe existed for the incident.
|
| 62 |
+
- If you believe this incident is ongoing.
|
| 63 |
+
- If you believe any member of the core team has a conflict of interest
|
| 64 |
+
in adjudicating the incident.
|
| 65 |
+
- What, if any, corrective response you believe would be appropriate.
|
| 66 |
+
- Any other information you believe we should have.
|
| 67 |
+
|
| 68 |
+
Core team members are obligated to maintain confidentiality with regard
|
| 69 |
+
to the reporter and details of an incident.
|
| 70 |
+
|
| 71 |
+
What happens next?
|
| 72 |
+
~~~~~~~~~~~~~~~~~~
|
| 73 |
+
|
| 74 |
+
You will receive an email acknowledging receipt of your complaint.
|
| 75 |
+
The core team will immediately meet to review the incident and determine:
|
| 76 |
+
|
| 77 |
+
- What happened.
|
| 78 |
+
- Whether this event constitutes a code of conduct violation.
|
| 79 |
+
- Who the bad actor was.
|
| 80 |
+
- Whether this is an ongoing situation, or if there is a threat to anyone's
|
| 81 |
+
physical safety.
|
| 82 |
+
- If this is determined to be an ongoing incident or a threat to physical safety,
|
| 83 |
+
the working groups' immediate priority will be to protect everyone involved.
|
| 84 |
+
|
| 85 |
+
If a member of the core team is one of the named parties, they will not be
|
| 86 |
+
included in any discussions, and will not be provided with any confidential
|
| 87 |
+
details from the reporter.
|
| 88 |
+
|
| 89 |
+
If anyone on the core team believes they have a conflict of interest in
|
| 90 |
+
adjudicating on a reported issue, they will inform the other core team
|
| 91 |
+
members, and exempt themselves from any discussion about the issue.
|
| 92 |
+
Following this declaration, they will not be provided with any confidential
|
| 93 |
+
details from the reporter.
|
| 94 |
+
|
| 95 |
+
Once the working group has a complete account of the events they will make a
|
| 96 |
+
decision as to how to response. Responses may include:
|
| 97 |
+
|
| 98 |
+
- Nothing (if we determine no violation occurred).
|
| 99 |
+
- A private reprimand from the working group to the individual(s) involved.
|
| 100 |
+
- A public reprimand.
|
| 101 |
+
- An imposed vacation
|
| 102 |
+
- A permanent or temporary ban from some or all spaces (GitHub repositories, etc.)
|
| 103 |
+
- A request for a public or private apology.
|
| 104 |
+
|
| 105 |
+
We'll respond within one week to the person who filed the report with either a
|
| 106 |
+
resolution or an explanation of why the situation is not yet resolved.
|
| 107 |
+
|
| 108 |
+
Once we've determined our final action, we'll contact the original reporter
|
| 109 |
+
to let them know what action (if any) we'll be taking. We'll take into account
|
| 110 |
+
feedback from the reporter on the appropriateness of our response, but we
|
| 111 |
+
don't guarantee we'll act on it.
|
| 112 |
+
|
| 113 |
+
Acknowledgement
|
| 114 |
+
---------------
|
| 115 |
+
|
| 116 |
+
This CoC is modified from the one by `BeeWare`_, which in turn refers to
|
| 117 |
+
the `Contributor Covenant`_ and the `Django`_ project.
|
| 118 |
+
|
| 119 |
+
.. _BeeWare: https://beeware.org/community/behavior/code-of-conduct/
|
| 120 |
+
.. _Contributor Covenant: https://www.contributor-covenant.org/version/1/3/0/code-of-conduct/
|
| 121 |
+
.. _Django: https://www.djangoproject.com/conduct/reporting/
|
| 122 |
+
|
| 123 |
+
.. raw:: html
|
| 124 |
+
|
| 125 |
+
<script data-goatcounter="https://projspec.goatcounter.com/count"
|
| 126 |
+
async src="//gc.zgo.at/count.js"></script>
|
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/conf.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# fsspec documentation build configuration file, created by
|
| 2 |
+
# sphinx-quickstart on Mon Jan 15 18:11:02 2018.
|
| 3 |
+
#
|
| 4 |
+
# This file is execfile()d with the current directory set to its
|
| 5 |
+
# containing dir.
|
| 6 |
+
#
|
| 7 |
+
# Note that not all possible configuration values are present in this
|
| 8 |
+
# autogenerated file.
|
| 9 |
+
#
|
| 10 |
+
# All configuration values have a default; values that are commented out
|
| 11 |
+
# serve to show the default.
|
| 12 |
+
|
| 13 |
+
# If extensions (or modules to document with autodoc) are in another directory,
|
| 14 |
+
# add these directories to sys.path here. If the directory is relative to the
|
| 15 |
+
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
| 16 |
+
#
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
sys.path.insert(0, os.path.abspath("../.."))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# -- General configuration ------------------------------------------------
|
| 24 |
+
|
| 25 |
+
# If your documentation needs a minimal Sphinx version, state it here.
|
| 26 |
+
#
|
| 27 |
+
# needs_sphinx = '1.0'
|
| 28 |
+
|
| 29 |
+
# Add any Sphinx extension module names here, as strings. They can be
|
| 30 |
+
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
|
| 31 |
+
# ones.
|
| 32 |
+
extensions = [
|
| 33 |
+
"sphinx.ext.autodoc",
|
| 34 |
+
"sphinx.ext.viewcode",
|
| 35 |
+
"sphinx.ext.autosummary",
|
| 36 |
+
"sphinx.ext.extlinks",
|
| 37 |
+
"numpydoc",
|
| 38 |
+
"sphinx_design",
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
numpydoc_show_class_members = False
|
| 42 |
+
|
| 43 |
+
# Add any paths that contain templates here, relative to this directory.
|
| 44 |
+
templates_path = ["_templates"]
|
| 45 |
+
|
| 46 |
+
# The suffix(es) of source filenames.
|
| 47 |
+
# You can specify multiple suffix as a list of string:
|
| 48 |
+
#
|
| 49 |
+
# source_suffix = ['.rst', '.md']
|
| 50 |
+
source_suffix = ".rst"
|
| 51 |
+
|
| 52 |
+
# The master toctree document.
|
| 53 |
+
master_doc = "index"
|
| 54 |
+
|
| 55 |
+
# General information about the project.
|
| 56 |
+
project = "fsspec"
|
| 57 |
+
copyright = "2018, Martin Durant"
|
| 58 |
+
author = "Martin Durant"
|
| 59 |
+
|
| 60 |
+
# The version info for the project you're documenting, acts as replacement for
|
| 61 |
+
# |version| and |release|, also used in various other places throughout the
|
| 62 |
+
# built documents.
|
| 63 |
+
#
|
| 64 |
+
# The short X.Y version.
|
| 65 |
+
|
| 66 |
+
import fsspec
|
| 67 |
+
|
| 68 |
+
version = fsspec.__version__
|
| 69 |
+
# The full version, including alpha/beta/rc tags.
|
| 70 |
+
release = fsspec.__version__
|
| 71 |
+
|
| 72 |
+
# List of patterns, relative to source directory, that match files and
|
| 73 |
+
# directories to ignore when looking for source files.
|
| 74 |
+
# This patterns also effect to html_static_path and html_extra_path
|
| 75 |
+
exclude_patterns = []
|
| 76 |
+
|
| 77 |
+
# The name of the Pygments (syntax highlighting) style to use.
|
| 78 |
+
pygments_style = "sphinx"
|
| 79 |
+
|
| 80 |
+
# If true, `todo` and `todoList` produce output, else they produce nothing.
|
| 81 |
+
todo_include_todos = False
|
| 82 |
+
|
| 83 |
+
default_role = "py:obj"
|
| 84 |
+
autodoc_mock_imports = [
|
| 85 |
+
"aiohttp",
|
| 86 |
+
"dask",
|
| 87 |
+
"distributed",
|
| 88 |
+
"fuse",
|
| 89 |
+
"libarchive",
|
| 90 |
+
"panel",
|
| 91 |
+
"paramiko",
|
| 92 |
+
"pyarrow",
|
| 93 |
+
"pygit2",
|
| 94 |
+
"requests",
|
| 95 |
+
"smbprotocol",
|
| 96 |
+
"smbclient",
|
| 97 |
+
]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# -- Options for HTML output ----------------------------------------------
|
| 101 |
+
|
| 102 |
+
# The theme to use for HTML and HTML Help pages. See the documentation for
|
| 103 |
+
# a list of builtin themes.
|
| 104 |
+
#
|
| 105 |
+
html_theme = "sphinx_rtd_theme"
|
| 106 |
+
|
| 107 |
+
# Theme options are theme-specific and customize the look and feel of a theme
|
| 108 |
+
# further. For a list of options available for each theme, see the
|
| 109 |
+
# documentation.
|
| 110 |
+
#
|
| 111 |
+
# html_theme_options = {}
|
| 112 |
+
|
| 113 |
+
# Add any paths that contain custom static files (such as style sheets) here,
|
| 114 |
+
# relative to this directory. They are copied after the builtin static files,
|
| 115 |
+
# so a file named "default.css" will overwrite the builtin "default.css".
|
| 116 |
+
html_static_path = ["_static"]
|
| 117 |
+
|
| 118 |
+
# Custom sidebar templates, must be a dictionary that maps document names
|
| 119 |
+
# to template names.
|
| 120 |
+
#
|
| 121 |
+
# This is required for the alabaster theme
|
| 122 |
+
# refs: https://alabaster.readthedocs.io/en/latest/installation.html#sidebars
|
| 123 |
+
html_sidebars = {
|
| 124 |
+
"**": [
|
| 125 |
+
"relations.html", # needs 'show_related': True theme option to display
|
| 126 |
+
"searchbox.html",
|
| 127 |
+
]
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
# Custom CSS file to override read the docs default CSS.
|
| 131 |
+
# Contains workaround for issue #790.
|
| 132 |
+
html_css_files = ["custom.css"]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# -- Options for HTMLHelp output ------------------------------------------
|
| 136 |
+
|
| 137 |
+
# Output file base name for HTML help builder.
|
| 138 |
+
htmlhelp_basename = "fsspecdoc"
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# -- Options for LaTeX output ---------------------------------------------
|
| 142 |
+
|
| 143 |
+
latex_elements = {
|
| 144 |
+
# The paper size ('letterpaper' or 'a4paper').
|
| 145 |
+
#
|
| 146 |
+
# 'papersize': 'letterpaper',
|
| 147 |
+
# The font size ('10pt', '11pt' or '12pt').
|
| 148 |
+
#
|
| 149 |
+
# 'pointsize': '10pt',
|
| 150 |
+
# Additional stuff for the LaTeX preamble.
|
| 151 |
+
#
|
| 152 |
+
# 'preamble': '',
|
| 153 |
+
# Latex figure (float) alignment
|
| 154 |
+
#
|
| 155 |
+
# 'figure_align': 'htbp',
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
# Grouping the document tree into LaTeX files. List of tuples
|
| 159 |
+
# (source start file, target name, title,
|
| 160 |
+
# author, documentclass [howto, manual, or own class]).
|
| 161 |
+
latex_documents = [
|
| 162 |
+
(master_doc, "fsspec.tex", "fsspec Documentation", "Joseph Crail", "manual")
|
| 163 |
+
]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# -- Options for manual page output ---------------------------------------
|
| 167 |
+
|
| 168 |
+
# One entry per manual page. List of tuples
|
| 169 |
+
# (source start file, name, description, authors, manual section).
|
| 170 |
+
man_pages = [(master_doc, "fsspec", "fsspec Documentation", [author], 1)]
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# -- Options for Texinfo output -------------------------------------------
|
| 174 |
+
|
| 175 |
+
# Grouping the document tree into Texinfo files. List of tuples
|
| 176 |
+
# (source start file, target name, title, author,
|
| 177 |
+
# dir menu entry, description, category)
|
| 178 |
+
texinfo_documents = [
|
| 179 |
+
(
|
| 180 |
+
master_doc,
|
| 181 |
+
"fsspec",
|
| 182 |
+
"fsspec Documentation",
|
| 183 |
+
author,
|
| 184 |
+
"fsspec",
|
| 185 |
+
"One line description of project.",
|
| 186 |
+
"Miscellaneous",
|
| 187 |
+
)
|
| 188 |
+
]
|
| 189 |
+
|
| 190 |
+
extlinks = {
|
| 191 |
+
"issue": ("https://github.com/fsspec/filesystem_spec/issues/%s", "GH#%s"),
|
| 192 |
+
"pr": ("https://github.com/fsspec/filesystem_spec/pull/%s", "GH#%s"),
|
| 193 |
+
}
|
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/copying.rst
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copying files and directories
|
| 2 |
+
=============================
|
| 3 |
+
|
| 4 |
+
This documents the expected behavior of the ``fsspec`` file and directory copying functions.
|
| 5 |
+
There are three functions of interest here: :meth:`~fsspec.spec.AbstractFileSystem.copy`,
|
| 6 |
+
:meth:`~fsspec.spec.AbstractFileSystem.get` and :meth:`~fsspec.spec.AbstractFileSystem.put`.
|
| 7 |
+
Each of these copies files and/or directories from a ``source`` to a ``target`` location.
|
| 8 |
+
If we refer to our filesystem of interest, derived from :class:`~fsspec.spec.AbstractFileSystem`,
|
| 9 |
+
as the remote filesystem (even though it may be local) then the difference between the three
|
| 10 |
+
functions is:
|
| 11 |
+
|
| 12 |
+
- :meth:`~fsspec.spec.AbstractFileSystem.copy` copies from a remote ``source`` to a remote ``target``
|
| 13 |
+
- :meth:`~fsspec.spec.AbstractFileSystem.get` copies from a remote ``source`` to a local ``target``
|
| 14 |
+
- :meth:`~fsspec.spec.AbstractFileSystem.put` copies from a local ``source`` to a remote ``target``
|
| 15 |
+
|
| 16 |
+
The ``source`` and ``target`` are the first two arguments passed to these functions, and each
|
| 17 |
+
consists of one or more files, directories and/or ``glob`` (wildcard) patterns.
|
| 18 |
+
The behavior of the ``fsspec`` copy functions is intended to be the same as that obtained using
|
| 19 |
+
POSIX command line ``cp`` but ``fsspec`` functions have extra functionality because:
|
| 20 |
+
|
| 21 |
+
- They support more than one ``target`` whereas command line ``cp`` is restricted to one.
|
| 22 |
+
- They can create new directories, either automatically or via the ``auto_mkdir=True`` keyword
|
| 23 |
+
argument, whereas command line ``cp`` only does this as part of a recursive copy.
|
| 24 |
+
|
| 25 |
+
Expected behavior
|
| 26 |
+
-----------------
|
| 27 |
+
|
| 28 |
+
There follows a comprehensive list of the expected behavior of the ``fsspec`` copying functions
|
| 29 |
+
that also forms the basis of a set of tests that all classes that derive from
|
| 30 |
+
:class:`~fsspec.spec.AbstractFileSystem` can be tested against to check that they conform.
|
| 31 |
+
For all scenarios the ``source`` filesystem contains the following directories and files::
|
| 32 |
+
|
| 33 |
+
📁 source
|
| 34 |
+
├── 📄 file1
|
| 35 |
+
├── 📄 file2
|
| 36 |
+
└── 📁 subdir
|
| 37 |
+
├── 📄 subfile1
|
| 38 |
+
├── 📄 subfile2
|
| 39 |
+
└── 📁 nesteddir
|
| 40 |
+
└── 📄 nestedfile
|
| 41 |
+
|
| 42 |
+
and before each scenario the ``target`` directory exists and is empty unless otherwise noted::
|
| 43 |
+
|
| 44 |
+
📁 target
|
| 45 |
+
|
| 46 |
+
All example code uses :meth:`~fsspec.spec.AbstractFileSystem.cp` which is an alias of
|
| 47 |
+
:meth:`~fsspec.spec.AbstractFileSystem.copy`; equivalent behavior is expected by
|
| 48 |
+
:meth:`~fsspec.spec.AbstractFileSystem.get` and :meth:`~fsspec.spec.AbstractFileSystem.put`.
|
| 49 |
+
Forward slashes are used for directory separators throughout.
|
| 50 |
+
|
| 51 |
+
1. Single source to single target
|
| 52 |
+
---------------------------------
|
| 53 |
+
|
| 54 |
+
.. dropdown:: 1a. File to existing directory
|
| 55 |
+
|
| 56 |
+
.. code-block:: python
|
| 57 |
+
|
| 58 |
+
cp("source/subdir/subfile1", "target/")
|
| 59 |
+
|
| 60 |
+
results in::
|
| 61 |
+
|
| 62 |
+
📁 target
|
| 63 |
+
└── 📄 subfile1
|
| 64 |
+
|
| 65 |
+
The trailing slash on ``"target/"`` is optional but recommended as it explicitly indicates that
|
| 66 |
+
the target is a directory.
|
| 67 |
+
|
| 68 |
+
.. dropdown:: 1b. File to new directory
|
| 69 |
+
|
| 70 |
+
.. code-block:: python
|
| 71 |
+
|
| 72 |
+
cp("source/subdir/subfile1", "target/newdir/")
|
| 73 |
+
|
| 74 |
+
results in::
|
| 75 |
+
|
| 76 |
+
📁 target
|
| 77 |
+
└── 📁 newdir
|
| 78 |
+
└── 📄 subfile1
|
| 79 |
+
|
| 80 |
+
This fails if the ``target`` file system is not capable of creating the directory, for example
|
| 81 |
+
if it is write-only or if ``auto_mkdir=False``. There is no command line equivalent of this
|
| 82 |
+
scenario without an explicit ``mkdir`` to create the new directory.
|
| 83 |
+
|
| 84 |
+
The trailing slash is required on the new directory otherwise it is interpreted as a filename
|
| 85 |
+
which is a different scenario (1d. File to file in new directory).
|
| 86 |
+
|
| 87 |
+
.. dropdown:: 1c. File to file in existing directory
|
| 88 |
+
|
| 89 |
+
.. code-block:: python
|
| 90 |
+
|
| 91 |
+
cp("source/subdir/subfile1", "target/newfile")
|
| 92 |
+
|
| 93 |
+
results in::
|
| 94 |
+
|
| 95 |
+
📁 target
|
| 96 |
+
└── 📄 newfile
|
| 97 |
+
|
| 98 |
+
The target cannot have a trailing slash as ``"newfile/"`` is interpreted as a new directory
|
| 99 |
+
which is a different scenario (1b. File to new directory).
|
| 100 |
+
|
| 101 |
+
.. dropdown:: 1d. File to file in new directory
|
| 102 |
+
|
| 103 |
+
.. code-block:: python
|
| 104 |
+
|
| 105 |
+
cp("source/subdir/subfile1", "target/newdir/newfile")
|
| 106 |
+
|
| 107 |
+
creates the new directory and copies the file into it::
|
| 108 |
+
|
| 109 |
+
📁 target
|
| 110 |
+
└── 📁 newdir
|
| 111 |
+
└── 📄 newfile
|
| 112 |
+
|
| 113 |
+
This fails if the ``target`` file system is not capable of creating the directory, for example
|
| 114 |
+
if it is write-only or if ``auto_mkdir=False``. There is no command line equivalent of this
|
| 115 |
+
scenario without an explicit ``mkdir`` to create the new directory.
|
| 116 |
+
|
| 117 |
+
If there is a trailing slash on the target ``target/newdir/newfile/`` then it is interpreted as
|
| 118 |
+
a new directory which is a different scenario (1b. File to new directory).
|
| 119 |
+
|
| 120 |
+
.. dropdown:: 1e. Directory to existing directory
|
| 121 |
+
|
| 122 |
+
.. code-block:: python
|
| 123 |
+
|
| 124 |
+
cp("source/subdir/", "target/", recursive=True)
|
| 125 |
+
|
| 126 |
+
results in::
|
| 127 |
+
|
| 128 |
+
��� target
|
| 129 |
+
├── 📄 subfile1
|
| 130 |
+
└── 📄 subfile2
|
| 131 |
+
└── 📁 nesteddir
|
| 132 |
+
└── 📄 nestedfile
|
| 133 |
+
|
| 134 |
+
The ``recursive=True`` keyword argument is required otherwise the call does nothing. The depth
|
| 135 |
+
of recursion can be controlled using the ``maxdepth`` keyword argument, for example:
|
| 136 |
+
|
| 137 |
+
.. code-block:: python
|
| 138 |
+
|
| 139 |
+
cp("source/subdir/", "target/", recursive=True, maxdepth=1)
|
| 140 |
+
|
| 141 |
+
results in::
|
| 142 |
+
|
| 143 |
+
📁 target
|
| 144 |
+
├── 📄 subfile1
|
| 145 |
+
└── 📄 subfile2
|
| 146 |
+
|
| 147 |
+
The trailing slash on ``"target/"`` is optional but recommended as it explicitly indicates that
|
| 148 |
+
the target is a directory.
|
| 149 |
+
|
| 150 |
+
If the trailing slash is omitted from ``"source/subdir"`` then the ``subdir`` is also copied,
|
| 151 |
+
not just its contents:
|
| 152 |
+
|
| 153 |
+
.. code-block:: python
|
| 154 |
+
|
| 155 |
+
cp("source/subdir", "target/", recursive=True)
|
| 156 |
+
|
| 157 |
+
results in::
|
| 158 |
+
|
| 159 |
+
📁 target
|
| 160 |
+
└── 📁 subdir
|
| 161 |
+
├── 📄 subfile1
|
| 162 |
+
└── 📄 subfile2
|
| 163 |
+
└── 📁 nesteddir
|
| 164 |
+
└── 📄 nestedfile
|
| 165 |
+
|
| 166 |
+
Again the depth of recursion can be controlled using the ``maxdepth`` keyword argument, for
|
| 167 |
+
example:
|
| 168 |
+
|
| 169 |
+
.. code-block:: python
|
| 170 |
+
|
| 171 |
+
cp("source/subdir", "target/", recursive=True, maxdepth=1)
|
| 172 |
+
|
| 173 |
+
results in::
|
| 174 |
+
|
| 175 |
+
📁 target
|
| 176 |
+
└── 📁 subdir
|
| 177 |
+
├── 📄 subfile1
|
| 178 |
+
└── 📄 subfile2
|
| 179 |
+
|
| 180 |
+
.. dropdown:: 1f. Directory to new directory
|
| 181 |
+
|
| 182 |
+
.. code-block:: python
|
| 183 |
+
|
| 184 |
+
cp("source/subdir/", "target/newdir/", recursive=True)
|
| 185 |
+
|
| 186 |
+
results in::
|
| 187 |
+
|
| 188 |
+
📁 target
|
| 189 |
+
└── 📁 newdir
|
| 190 |
+
├── 📄 subfile1
|
| 191 |
+
└── 📄 subfile2
|
| 192 |
+
└── 📁 nesteddir
|
| 193 |
+
└── 📄 nestedfile
|
| 194 |
+
|
| 195 |
+
Trailing slashes on both ``source`` and ``target`` are optional and do not affect the result.
|
| 196 |
+
They are recommended to explicitly indicate both are directories.
|
| 197 |
+
|
| 198 |
+
The ``recursive=True`` keyword argument is required otherwise the call does nothing. The depth
|
| 199 |
+
of recursion can be controlled using the ``maxdepth`` keyword argument, for example:
|
| 200 |
+
|
| 201 |
+
.. code-block:: python
|
| 202 |
+
|
| 203 |
+
cp("source/subdir/", "target/newdir/", recursive=True, maxdepth=1)
|
| 204 |
+
|
| 205 |
+
results in::
|
| 206 |
+
|
| 207 |
+
📁 target
|
| 208 |
+
└── 📁 newdir
|
| 209 |
+
├── 📄 subfile1
|
| 210 |
+
└── 📄 subfile2
|
| 211 |
+
|
| 212 |
+
.. dropdown:: 1g. Glob to existing directory
|
| 213 |
+
|
| 214 |
+
Nonrecursive
|
| 215 |
+
|
| 216 |
+
.. code-block:: python
|
| 217 |
+
|
| 218 |
+
cp("source/subdir/*", "target/")
|
| 219 |
+
|
| 220 |
+
copies files from the top-level directory only and results in::
|
| 221 |
+
|
| 222 |
+
📁 target
|
| 223 |
+
├── 📄 subfile1
|
| 224 |
+
└── 📄 subfile2
|
| 225 |
+
|
| 226 |
+
Recursive
|
| 227 |
+
|
| 228 |
+
.. code-block:: python
|
| 229 |
+
|
| 230 |
+
cp("source/subdir/*", "target/", recursive=True)
|
| 231 |
+
|
| 232 |
+
results in::
|
| 233 |
+
|
| 234 |
+
📁 target
|
| 235 |
+
├── 📄 subfile1
|
| 236 |
+
└── 📄 subfile2
|
| 237 |
+
└── 📁 nesteddir
|
| 238 |
+
└── 📄 nestedfile
|
| 239 |
+
|
| 240 |
+
The trailing slash on ``"target/"`` is optional but recommended as it explicitly indicates that
|
| 241 |
+
the target is a directory.
|
| 242 |
+
|
| 243 |
+
The depth of recursion can be controlled by the ``maxdepth`` keyword argument, for example:
|
| 244 |
+
|
| 245 |
+
.. code-block:: python
|
| 246 |
+
|
| 247 |
+
cp("source/subdir/*", "target/", recursive=True, maxdepth=1)
|
| 248 |
+
|
| 249 |
+
results in::
|
| 250 |
+
|
| 251 |
+
📁 target
|
| 252 |
+
├── 📄 subfile1
|
| 253 |
+
└── 📄 subfile2
|
| 254 |
+
|
| 255 |
+
.. dropdown:: 1h. Glob to new directory
|
| 256 |
+
|
| 257 |
+
Nonrecursive
|
| 258 |
+
|
| 259 |
+
.. code-block:: python
|
| 260 |
+
|
| 261 |
+
cp("source/subdir/*", "target/newdir/")
|
| 262 |
+
|
| 263 |
+
copies files from the top-level directory only and results in::
|
| 264 |
+
|
| 265 |
+
📁 target
|
| 266 |
+
└── 📁 newdir
|
| 267 |
+
├── 📄 subfile1
|
| 268 |
+
└── 📄 subfile2
|
| 269 |
+
|
| 270 |
+
Recursive
|
| 271 |
+
|
| 272 |
+
.. code-block:: python
|
| 273 |
+
|
| 274 |
+
cp("source/subdir/*", "target/newdir/", recursive=True)
|
| 275 |
+
|
| 276 |
+
results in::
|
| 277 |
+
|
| 278 |
+
📁 target
|
| 279 |
+
└── 📁 newdir
|
| 280 |
+
├── 📄 subfile1
|
| 281 |
+
└── 📄 subfile2
|
| 282 |
+
└── 📁 nesteddir
|
| 283 |
+
└── 📄 nestedfile
|
| 284 |
+
|
| 285 |
+
The trailing slash on the ``target`` is optional but recommended as it explicitly indicates that
|
| 286 |
+
it is a directory.
|
| 287 |
+
|
| 288 |
+
The depth of recursion can be controlled by the ``maxdepth`` keyword argument, for example:
|
| 289 |
+
|
| 290 |
+
.. code-block:: python
|
| 291 |
+
|
| 292 |
+
cp("source/subdir/*", "target/newdir/", recursive=True, maxdepth=1)
|
| 293 |
+
|
| 294 |
+
results in::
|
| 295 |
+
|
| 296 |
+
📁 target
|
| 297 |
+
└── 📁 newdir
|
| 298 |
+
├── 📄 subfile1
|
| 299 |
+
└── 📄 subfile2
|
| 300 |
+
|
| 301 |
+
These calls fail if the ``target`` file system is not capable of creating the directory, for
|
| 302 |
+
example if it is write-only or if ``auto_mkdir=False``. There is no command line equivalent of
|
| 303 |
+
this scenario without an explicit ``mkdir`` to create the new directory.
|
| 304 |
+
|
| 305 |
+
2. Multiple source to single target
|
| 306 |
+
-----------------------------------
|
| 307 |
+
|
| 308 |
+
.. dropdown:: 2a. List of files to existing directory
|
| 309 |
+
|
| 310 |
+
.. code-block:: python
|
| 311 |
+
|
| 312 |
+
cp(["source/file1", "source/file2", "source/subdir/subfile1"], "target/")
|
| 313 |
+
|
| 314 |
+
results in::
|
| 315 |
+
|
| 316 |
+
📁 target
|
| 317 |
+
├── 📄 file1
|
| 318 |
+
├── 📄 file2
|
| 319 |
+
└── 📄 subfile1
|
| 320 |
+
|
| 321 |
+
All of the files are copied to the target directory regardless of their relative paths in the
|
| 322 |
+
source filesystem. The trailing slash on the ``target`` is optional but recommended as it
|
| 323 |
+
explicitly indicates that it is a directory.
|
| 324 |
+
|
| 325 |
+
.. dropdown:: 2b. List of files to new directory
|
| 326 |
+
|
| 327 |
+
.. code-block:: python
|
| 328 |
+
|
| 329 |
+
cp(["source/file1", "source/file2", "source/subdir/subfile1"], "target/newdir/")
|
| 330 |
+
|
| 331 |
+
results in::
|
| 332 |
+
|
| 333 |
+
📁 target
|
| 334 |
+
└── 📁 newdir
|
| 335 |
+
├── 📄 file1
|
| 336 |
+
├── 📄 file2
|
| 337 |
+
└── 📄 subfile1
|
| 338 |
+
|
| 339 |
+
All of the files are copied to the target directory regardless of their relative paths in the
|
| 340 |
+
source filesystem.
|
| 341 |
+
|
| 342 |
+
The trailing slash is required on the new directory otherwise it is interpreted as a filename
|
| 343 |
+
rather than a directory.
|
| 344 |
+
|
| 345 |
+
.. raw:: html
|
| 346 |
+
|
| 347 |
+
<script data-goatcounter="https://fsspec.goatcounter.com/count"
|
| 348 |
+
async src="//gc.zgo.at/count.js"></script>
|
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/developer.rst
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Developing with fsspec
|
| 2 |
+
----------------------
|
| 3 |
+
|
| 4 |
+
Whereas the majority of the documentation describes the use of ``fsspec``
|
| 5 |
+
from the end-user's point of view, ``fsspec`` is used by many libraries
|
| 6 |
+
as the primary/only interface to file operations.
|
| 7 |
+
|
| 8 |
+
Clients of the library
|
| 9 |
+
~~~~~~~~~~~~~~~~~~~~~~
|
| 10 |
+
|
| 11 |
+
The most common entrance point for libraries which wish to rely on ``fsspec``
|
| 12 |
+
will be ``open`` or ``open_files``, as a way of generating an object compatible
|
| 13 |
+
with the python file interface. This actually produces an ``OpenFile`` instance,
|
| 14 |
+
which can be serialised across a network, and resources are only engaged when
|
| 15 |
+
entering a context, e.g.
|
| 16 |
+
|
| 17 |
+
.. code-block:: python
|
| 18 |
+
|
| 19 |
+
with fsspec.open("protocol://path", 'rb', param=value) as f:
|
| 20 |
+
process_file(f)
|
| 21 |
+
|
| 22 |
+
Note the backend-specific parameters that can be passed in this call.
|
| 23 |
+
|
| 24 |
+
In cases where the caller wants to control the context directly, they can use the
|
| 25 |
+
``open`` method of the ``OpenFile``, or get the filesystem object directly,
|
| 26 |
+
skipping the ``OpenFile`` route. In the latter case, text encoding and compression
|
| 27 |
+
are **not** handled for you. The file-like object can also be used as a context
|
| 28 |
+
manager, or the ``close()`` method must be called explicitly to release resources.
|
| 29 |
+
|
| 30 |
+
.. code-block:: python
|
| 31 |
+
|
| 32 |
+
# OpenFile route
|
| 33 |
+
of = fsspec.open("protocol://path", 'rb', param=value)
|
| 34 |
+
f = of.open()
|
| 35 |
+
process_file(f)
|
| 36 |
+
f.close()
|
| 37 |
+
|
| 38 |
+
# filesystem class route, context
|
| 39 |
+
fs = fsspec.filesystem("protocol", param=value)
|
| 40 |
+
with fs.open("path", "rb") as f:
|
| 41 |
+
process_file(f)
|
| 42 |
+
|
| 43 |
+
# filesystem class route, explicit close
|
| 44 |
+
fs = fsspec.filesystem("protocol", param=value)
|
| 45 |
+
f = fs.open("path", "rb")
|
| 46 |
+
process_file(f)
|
| 47 |
+
f.close()
|
| 48 |
+
|
| 49 |
+
Implementing a backend
|
| 50 |
+
~~~~~~~~~~~~~~~~~~~~~~
|
| 51 |
+
|
| 52 |
+
The class ``AbstractFileSystem`` provides a template of the methods
|
| 53 |
+
that a potential implementation should supply, as well as default
|
| 54 |
+
implementation of functionality that depends on these. Methods that
|
| 55 |
+
*could* be implemented are marked with ``NotImplementedError`` or
|
| 56 |
+
``pass`` (the latter specifically for directory operations that might
|
| 57 |
+
not be required for some backends where directories are emulated.
|
| 58 |
+
|
| 59 |
+
Note that not all of the methods need to be implemented: for example,
|
| 60 |
+
some implementations may be read-only, in which case things like ``pipe``,
|
| 61 |
+
``put``, ``touch``, ``rm``, etc., can be left as not-implemented
|
| 62 |
+
(or you might implement them and raise PermissionError, OSError 30 or some
|
| 63 |
+
read-only exception).
|
| 64 |
+
|
| 65 |
+
We may eventually refactor ``AbstractFileSystem`` to split the default implementation,
|
| 66 |
+
the set of methods that you might implement in a new backend, and the
|
| 67 |
+
documented end-user API.
|
| 68 |
+
|
| 69 |
+
In order to register a new backend with fsspec, new backends should register
|
| 70 |
+
themselves using the `entry_points <https://setuptools.readthedocs.io/en/latest/userguide/quickstart.html#entry-points-and-automatic-script-creation>`_
|
| 71 |
+
facility from setuptools. In particular, if you want to register a new
|
| 72 |
+
filesystem protocol ``myfs`` which is provided by the ``MyFS`` class in
|
| 73 |
+
the ``myfs`` package, add the following to your ``setup.py``:
|
| 74 |
+
|
| 75 |
+
.. code-block:: python
|
| 76 |
+
|
| 77 |
+
setuptools.setup(
|
| 78 |
+
...
|
| 79 |
+
entry_points={
|
| 80 |
+
'fsspec.specs': [
|
| 81 |
+
'myfs=myfs.MyFS',
|
| 82 |
+
],
|
| 83 |
+
},
|
| 84 |
+
...
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
Alternatively, the previous method of registering a new backend can be used.
|
| 89 |
+
That is, new backends must register themselves on import
|
| 90 |
+
(``register_implementation``) or post a PR to the ``fsspec`` repo
|
| 91 |
+
asking to be included in ``fsspec.registry.known_implementations``.
|
| 92 |
+
|
| 93 |
+
Implementing async
|
| 94 |
+
~~~~~~~~~~~~~~~~~~
|
| 95 |
+
|
| 96 |
+
Starting in version 0.7.5, we provide async operations for some methods
|
| 97 |
+
of some implementations. Async support in storage implementations is
|
| 98 |
+
optional. Special considerations are required for async
|
| 99 |
+
development, see :doc:`async`.
|
| 100 |
+
|
| 101 |
+
Developing the library
|
| 102 |
+
~~~~~~~~~~~~~~~~~~~~~~
|
| 103 |
+
|
| 104 |
+
The following can be used to install ``fsspec`` in development mode
|
| 105 |
+
|
| 106 |
+
.. code-block::
|
| 107 |
+
|
| 108 |
+
git clone https://github.com/fsspec/filesystem_spec
|
| 109 |
+
cd filesystem_spec
|
| 110 |
+
pip install -e .[dev,doc,test]
|
| 111 |
+
|
| 112 |
+
A number of additional dependencies are required to run tests in full, see "ci/environment*.yml", as
|
| 113 |
+
well as Docker. Most implementation-specific tests should skip if their requirements are
|
| 114 |
+
not met.
|
| 115 |
+
|
| 116 |
+
Development happens by submitting pull requests (PRs) on github.
|
| 117 |
+
This repo uses Ruff for Python linting and formatting. Run ``ruff check fsspec``
|
| 118 |
+
and ``ruff format --check fsspec`` from the repository root to check your changes.
|
| 119 |
+
Run ``ruff format fsspec`` to apply formatting. You may wish to install
|
| 120 |
+
the project's commit hooks with ``pre-commit install --install-hooks``, as
|
| 121 |
+
linting is done as part of the CI. Run ``pre-commit run --all-files`` to run all
|
| 122 |
+
configured hooks without making a commit.
|
| 123 |
+
|
| 124 |
+
Docs use sphinx and the numpy docstring style. Please add an entry to the changelog
|
| 125 |
+
along with any PR.
|
| 126 |
+
|
| 127 |
+
.. raw:: html
|
| 128 |
+
|
| 129 |
+
<script data-goatcounter="https://fsspec.goatcounter.com/count"
|
| 130 |
+
async src="//gc.zgo.at/count.js"></script>
|
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/features.rst
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 3 |
+
|
| 4 |
+
Here follows a brief description of some features of note of ``fsspec`` that provides to make
|
| 5 |
+
it an interesting project beyond some other file-system abstractions.
|
| 6 |
+
|
| 7 |
+
Serialisability
|
| 8 |
+
---------------
|
| 9 |
+
|
| 10 |
+
Coming out of the Dask stable, it was an important design decision that file-system instances
|
| 11 |
+
be serialisable, so that they could be created in one process (e.g., the client) and used in
|
| 12 |
+
other processes (typically the workers). These other processes may even be on other machines,
|
| 13 |
+
so in many cases they would need to be able to re-establish credentials, ideally without passing
|
| 14 |
+
sensitive tokens in the pickled binary data.
|
| 15 |
+
|
| 16 |
+
``fsspec`` instances, generally speaking, abide by these rules, do not include locks, files and other
|
| 17 |
+
thread-local material, and where possible, use local credentials (such as a token file)
|
| 18 |
+
for re-establishing sessions upon de-serialisation. (While making use of cached instances, where
|
| 19 |
+
they exist, see below).
|
| 20 |
+
|
| 21 |
+
``OpenFile`` instances
|
| 22 |
+
----------------------
|
| 23 |
+
|
| 24 |
+
The :func:`fsspec.core.OpenFile` class provides a convenient way to prescribe the manner to
|
| 25 |
+
open some file (local,
|
| 26 |
+
remote, in a compressed store, etc.) which is portable, and can also apply any compression and
|
| 27 |
+
text-mode to the file. These instances are also serialisable, because they do not contain any open
|
| 28 |
+
files.
|
| 29 |
+
|
| 30 |
+
The way to work with ``OpenFile`` s is to isolate interaction with in a ``with`` context. It is
|
| 31 |
+
the initiation of the context which actually does the work of creating file-like instances.
|
| 32 |
+
|
| 33 |
+
.. code-block:: python
|
| 34 |
+
|
| 35 |
+
of = fsspec.open(url, ...)
|
| 36 |
+
# of is just a place-holder
|
| 37 |
+
with of as f:
|
| 38 |
+
# f is now a real file-like object holding resources
|
| 39 |
+
f.read(...)
|
| 40 |
+
|
| 41 |
+
File Buffering and random access
|
| 42 |
+
--------------------------------
|
| 43 |
+
|
| 44 |
+
Most implementations create file objects which derive from ``fsspec.spec.AbstractBufferedFile``, and
|
| 45 |
+
have many behaviours in common. A subclass of ``AbstractBufferedFile`` provides
|
| 46 |
+
random access for the underlying file-like data (without downloading the whole thing).
|
| 47 |
+
This is a critical feature in the big-data access model, where each sub-task of an operation
|
| 48 |
+
may need on a small part of a file, and does not, therefore want to be forced into downloading the
|
| 49 |
+
whole thing.
|
| 50 |
+
|
| 51 |
+
These files offer buffering of both read and write operations, so that
|
| 52 |
+
communication with the remote resource is limited. The size of the buffer is generally configured
|
| 53 |
+
with the ``blocksize=`` kwarg at open time, although the implementation may have some minimum or
|
| 54 |
+
maximum sizes that need to be respected.
|
| 55 |
+
|
| 56 |
+
For reading, a number of buffering schemes are available, listed in ``fsspec.caching.caches``
|
| 57 |
+
(see :ref:`readbuffering`), or "none" for no buffering at all, e.g., for a simple read-ahead
|
| 58 |
+
buffer, you can do
|
| 59 |
+
|
| 60 |
+
.. code-block:: python
|
| 61 |
+
|
| 62 |
+
fs = fsspec.filesystem(...)
|
| 63 |
+
with fs.open(path, mode='rb', cache_type='readahead') as f:
|
| 64 |
+
use_for_something(f)
|
| 65 |
+
|
| 66 |
+
Transparent text-mode and compression
|
| 67 |
+
-------------------------------------
|
| 68 |
+
|
| 69 |
+
As mentioned above, the ``OpenFile`` class allows for the opening of files on a binary store,
|
| 70 |
+
which appear to be in text mode and/or allow for a compression/decompression layer between the
|
| 71 |
+
caller and the back-end storage system. The list of ``fsspec`` supported codec
|
| 72 |
+
can be retrieved using :func:`fsspec.available_compressions`.
|
| 73 |
+
From the user's point of view, this is achieved simply by passing arguments to
|
| 74 |
+
the :func:`fsspec.open_files` or :func:`fsspec.open` functions, and
|
| 75 |
+
thereafter happens transparently.
|
| 76 |
+
|
| 77 |
+
Key-value stores
|
| 78 |
+
----------------
|
| 79 |
+
|
| 80 |
+
File-systems are naturally like dict-like key-value mappings: each (string) path corresponds to some
|
| 81 |
+
binary data on the storage back-end. For some use-cases, it is very convenient to be able to
|
| 82 |
+
view some path within the file-system as a dict-like store, and the function :func:`fsspec.get_mapper`
|
| 83 |
+
gives a one-stop way to return such an object. This has become useful, for example, in the
|
| 84 |
+
context of the `zarr`_ project, which stores it array chunks in keys in any arbitrary mapping-like
|
| 85 |
+
object.
|
| 86 |
+
|
| 87 |
+
.. code-block:: python
|
| 88 |
+
|
| 89 |
+
mapper = fsspec.get_mapper('protocol://server/path', args)
|
| 90 |
+
list(mapper)
|
| 91 |
+
mapper[k] = b'some data'
|
| 92 |
+
|
| 93 |
+
.. _zarr: https://zarr.readthedocs.io/en/stable/
|
| 94 |
+
|
| 95 |
+
PyArrow integration
|
| 96 |
+
-------------------
|
| 97 |
+
|
| 98 |
+
`pyarrow`_ has its own internal idea of what a file-system is (``pyarrow.fs.FileSystem``),
|
| 99 |
+
and some functions, particularly the loading of parquet, require that the target be compatible.
|
| 100 |
+
As it happens, the design of the file-system interface in ``pyarrow`` *is* compatible with ``fsspec``
|
| 101 |
+
(this is not by accident).
|
| 102 |
+
|
| 103 |
+
At import time, ``fsspec`` checks for the existence of ``pyarrow``, and, if ``pyarrow < 2.0`` is
|
| 104 |
+
found, adds its base filesystem to the superclasses of the spec base-class.
|
| 105 |
+
For ``pyarrow >= 2.0``, ``fsspec`` file systems can simply be passed to ``pyarrow`` functions
|
| 106 |
+
that expect ``pyarrow`` filesystems, and ``pyarrow`` `will automatically wrap them
|
| 107 |
+
<https://arrow.apache.org/docs/python/filesystems.html#using-fsspec-compatible-filesystems>`_.
|
| 108 |
+
|
| 109 |
+
In this manner, all ``fsspec``-derived file-systems are also ``pyarrow`` file-systems, and can be used
|
| 110 |
+
by ``pyarrow`` functions.
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
.. _pyarrow: https://arrow.apache.org/docs/python/
|
| 114 |
+
|
| 115 |
+
Transactions
|
| 116 |
+
------------
|
| 117 |
+
|
| 118 |
+
``fsspec`` supports *transactions*, during which writing to files on a remote store is deferred
|
| 119 |
+
(typically put into a temporary location) until the transaction is over, whereupon the whole
|
| 120 |
+
transaction is finalised in a semi-atomic way, and all the files are moved/committed to their
|
| 121 |
+
final destination. The implementation of the details is file-system specific (and not all
|
| 122 |
+
support it yet), but the idea is,
|
| 123 |
+
that all files should get written or none, to mitigate against data corruption. The feature
|
| 124 |
+
can be used like
|
| 125 |
+
|
| 126 |
+
.. code-block:: python
|
| 127 |
+
|
| 128 |
+
fs = fsspec.filesystem(...)
|
| 129 |
+
with fs.transaction:
|
| 130 |
+
with fs.open('file1', 'wb') as f:
|
| 131 |
+
f.write(b'some data')
|
| 132 |
+
with fs.open('file2', 'wb') as f:
|
| 133 |
+
f.write(b'more data')
|
| 134 |
+
|
| 135 |
+
Here, files 1 and 2 do not get moved to the target location until the transaction context finishes.
|
| 136 |
+
If the context finishes due to an (uncaught) exception, then the files are discarded and the
|
| 137 |
+
file target locations untouched.
|
| 138 |
+
|
| 139 |
+
The class :func:`fsspec.spec.Transaction` allows for fine-tuning of the operation, and every
|
| 140 |
+
``fsspec`` instance has an instance of this as an attribute ``.transaction`` to give access.
|
| 141 |
+
|
| 142 |
+
Note that synchronising transactions across multiple instances, perhaps across a cluster,
|
| 143 |
+
is a harder problem to solve, and the implementation described here is only part of the solution.
|
| 144 |
+
|
| 145 |
+
Mount anything with FUSE
|
| 146 |
+
------------------------
|
| 147 |
+
|
| 148 |
+
Any path of any file-system can be mapped to a local directory using `fusepy <https://pypi.org/project/fusepy/>`_ and
|
| 149 |
+
:func:`fsspec.fuse.run`. This feature is experimental, but basic file listing with
|
| 150 |
+
details, and read/write should generally be available to the extent that the
|
| 151 |
+
remote file-system provides enough information. Naturally, if a file-system is read-only,
|
| 152 |
+
then write operations will fail - but they will tend to fail late and with obscure
|
| 153 |
+
error messages such as "bad address".
|
| 154 |
+
|
| 155 |
+
Some specific quirks of some file-systems may cause confusion for FUSE. For example,
|
| 156 |
+
it is possible for a given path on s3 to be both a valid key (i.e., containing binary
|
| 157 |
+
data, like a file) and a valid prefix (i.e., can be listed to find subkeys, like a
|
| 158 |
+
directory). Since this breaks the assumptions of a normal file-system, it may not
|
| 159 |
+
be possible to reach all paths on the remote.
|
| 160 |
+
|
| 161 |
+
Instance Caching
|
| 162 |
+
----------------
|
| 163 |
+
|
| 164 |
+
If a file-system implementation class is marked as *cachable* (attribute ``.cachable``),
|
| 165 |
+
then its instances will
|
| 166 |
+
get stored in a class attribute, to enable quick look-up instead of needing to regenerate
|
| 167 |
+
potentially expensive connections and sessions. They key in the cache is a tokenisation of
|
| 168 |
+
the arguments to create the instance. The cache itself (attribute ``._cache``)
|
| 169 |
+
is currently a simple dict, but could in the future be LRU, or something more complicated,
|
| 170 |
+
to fine-tune instance lifetimes.
|
| 171 |
+
|
| 172 |
+
Since files can hold on to write caches and read buffers,
|
| 173 |
+
the instance cache may cause excessive memory usage in some situations; but normally, files'
|
| 174 |
+
``close`` methods will be called, discarding the data. Only when there is also an unfinalised transaction or
|
| 175 |
+
captured traceback might this be anticipated becoming a problem.
|
| 176 |
+
|
| 177 |
+
To disable instance caching, i.e., get a fresh instance which is not in the cache
|
| 178 |
+
even for a cachable class, pass ``skip_instance_cache=True``.
|
| 179 |
+
|
| 180 |
+
Memory filesystems
|
| 181 |
+
------------------
|
| 182 |
+
|
| 183 |
+
Memory filesystem instances share their files and directories by default and
|
| 184 |
+
use the normal instance cache. To create independent stores, pass
|
| 185 |
+
``global_store=False, skip_instance_cache=True`` and retain the instance for
|
| 186 |
+
subsequent operations. Without ``skip_instance_cache=True``, the normal instance
|
| 187 |
+
cache applies: repeated calls with the same arguments reuse the same instance
|
| 188 |
+
and its store:
|
| 189 |
+
|
| 190 |
+
.. code-block:: python
|
| 191 |
+
|
| 192 |
+
first = fsspec.filesystem("memory", global_store=False, skip_instance_cache=True)
|
| 193 |
+
second = fsspec.filesystem("memory", global_store=False, skip_instance_cache=True)
|
| 194 |
+
first.pipe("file", b"data")
|
| 195 |
+
assert not second.exists("file")
|
| 196 |
+
|
| 197 |
+
Pickling an independent memory filesystem copies its files and directories.
|
| 198 |
+
The default global filesystem continues to use the global store in the process
|
| 199 |
+
where it is unpickled.
|
| 200 |
+
|
| 201 |
+
Listings Caching
|
| 202 |
+
----------------
|
| 203 |
+
|
| 204 |
+
For some implementations, getting file listings (i.e., ``ls`` and anything that
|
| 205 |
+
depends on it) is expensive. These implementations use dict-like instances of
|
| 206 |
+
:class:`fsspec.dircache.DirCache` to manage the listings.
|
| 207 |
+
|
| 208 |
+
The cache allows for time-based expiry of entries with the ``listings_expiry_time``
|
| 209 |
+
parameter, or LRU expiry with the ``max_paths`` parameter. These can be
|
| 210 |
+
set on any implementation instance that uses listings caching; or to skip the
|
| 211 |
+
caching altogether, use ``use_listings_cache=False``. That would be appropriate
|
| 212 |
+
when the target location is known to be volatile because it is being written
|
| 213 |
+
to from other sources.
|
| 214 |
+
|
| 215 |
+
When the ``fsspec`` instance writes to the backend, the method ``invalidate_cache``
|
| 216 |
+
is called, so that subsequent listing of the given paths will force a refresh. In
|
| 217 |
+
addition, some methods like ``ls`` have a ``refresh`` parameter to force fetching
|
| 218 |
+
the listing again.
|
| 219 |
+
|
| 220 |
+
URL chaining
|
| 221 |
+
------------
|
| 222 |
+
|
| 223 |
+
Some implementations proxy or otherwise make use of another filesystem implementation, such
|
| 224 |
+
as locally caching remote files, i.e., finding out what files exist using the remote implementation,
|
| 225 |
+
but actually opening the local copies upon access. Other examples include reading from a Dask worker
|
| 226 |
+
which can see file-systems the client cannot, and accessing a zip file which is being read from
|
| 227 |
+
another backend.
|
| 228 |
+
|
| 229 |
+
In such cases, you can specify the parameters exactly as specified in the implementation docstrings,
|
| 230 |
+
for the dask case something like
|
| 231 |
+
|
| 232 |
+
.. code-block:: python
|
| 233 |
+
|
| 234 |
+
of = fsspec.open('dask://bucket/key', target_protocol='s3', target_options={'anon': True})
|
| 235 |
+
|
| 236 |
+
As a shorthand, particularly useful where you have multiple hops, is to "chain" the URLs with
|
| 237 |
+
the special separator ``"::"``. The arguments to be passed on to each of the implementations referenced
|
| 238 |
+
are keyed by the protocol names included in the URL. Here is the equivalent to the line above:
|
| 239 |
+
|
| 240 |
+
.. code-block:: python
|
| 241 |
+
|
| 242 |
+
of = fsspec.open('dask::s3://bucket/key', s3={'anon': True})
|
| 243 |
+
|
| 244 |
+
A couple of more complicated cases:
|
| 245 |
+
|
| 246 |
+
.. code-block:: python
|
| 247 |
+
|
| 248 |
+
of = fsspec.open_files('zip://*.csv::simplecache::gcs://bucket/afile.zip',
|
| 249 |
+
simplecache={'cache_storage': '/stored/zip/files'},
|
| 250 |
+
gcs={'project': 'my-project'})
|
| 251 |
+
|
| 252 |
+
reads a zip-file from google, stores it locally, and gives access to the contained CSV files. Conversely,
|
| 253 |
+
|
| 254 |
+
.. code-block:: python
|
| 255 |
+
|
| 256 |
+
of = fsspec.open_files('simplecache::zip://*.csv::gcs://bucket/afile.zip',
|
| 257 |
+
simplecache={'cache_storage': '/stored/csv/files'},
|
| 258 |
+
gcs={'project': 'my-project'})
|
| 259 |
+
|
| 260 |
+
reads the same zip-file, but extracts the CSV files and stores them locally in the cache.
|
| 261 |
+
|
| 262 |
+
**For developers**: this "chaining" methods works by formatting the arguments passed to ``open_*``
|
| 263 |
+
into ``target_protocol`` (a simple string) and ``target_options`` (a dict) and also optionally
|
| 264 |
+
``fo`` (target path, if a specific file is required). In order for an implementation to chain
|
| 265 |
+
successfully like this, it must look for exactly those named arguments. Implementations that
|
| 266 |
+
require access to the target path of their nested targets should inherit from ``ChainedFileSystem``,
|
| 267 |
+
which will trigger pass-through of the nested path automatically.
|
| 268 |
+
|
| 269 |
+
Caching Files Locally
|
| 270 |
+
---------------------
|
| 271 |
+
|
| 272 |
+
``fsspec`` allows you to access data on remote file systems, that is its purpose. However, such
|
| 273 |
+
access can often be rather slow compared to local storage, so as well as buffering (see above), the
|
| 274 |
+
option exists to copy files locally when you first access them, and thereafter to use the local data.
|
| 275 |
+
This local cache of data might be temporary (i.e., attached to the process and discarded when the
|
| 276 |
+
process ends) or at some specific location in your local storage.
|
| 277 |
+
|
| 278 |
+
Two mechanisms are provided, and both involve wrapping a ``target`` filesystem. The following example
|
| 279 |
+
creates a file-based cache.
|
| 280 |
+
|
| 281 |
+
.. code-block:: python
|
| 282 |
+
|
| 283 |
+
fs = fsspec.filesystem("filecache", target_protocol='s3', target_options={'anon': True},
|
| 284 |
+
cache_storage='/tmp/files/')
|
| 285 |
+
|
| 286 |
+
Each time you open a remote file on S3, it will first copy it to
|
| 287 |
+
a local temporary directory, and then all further access will use the local file. Since we specify
|
| 288 |
+
a particular local location, the files will persist and can be reused from future sessions, although
|
| 289 |
+
you can also set policies to have cached files expire after some time, or to check the remote file system
|
| 290 |
+
on each open, to see if the target file has changed since it was copied.
|
| 291 |
+
|
| 292 |
+
With the top-level functions ``open``, ``open_local`` and ``open_files``, you can use the
|
| 293 |
+
same set of kwargs as the example above, or you can chain the URL - the following would
|
| 294 |
+
be the equivalent
|
| 295 |
+
|
| 296 |
+
.. code-block:: python
|
| 297 |
+
|
| 298 |
+
of = fsspec.open("filecache::s3://bucket/key",
|
| 299 |
+
s3={'anon': True}, filecache={'cache_storage':'/tmp/files'})
|
| 300 |
+
|
| 301 |
+
With the "blockcache" variant, data is downloaded block-wise: only the specific parts of the remote file
|
| 302 |
+
which are accessed. This means that the local copy of the file might end up being much smaller than the
|
| 303 |
+
remote one, if only certain parts of it are required.
|
| 304 |
+
|
| 305 |
+
Whereas "filecache" works for all file system implementations, and provides a real local file for other
|
| 306 |
+
libraries to use, "blockcache" has restrictions: that you have a storage/OS combination which supports
|
| 307 |
+
sparse files, that the backend implementation uses files which derive ``from AbstractBufferedFile``,
|
| 308 |
+
and that the library you pass the resultant object to accepts generic python file-like objects. You
|
| 309 |
+
should not mix block- and file-caches in the same directory. "simplecache" is the same as "filecache",
|
| 310 |
+
except without the options for cache expiry and to check the original source - it can be used where the
|
| 311 |
+
target can be considered static, and particularly where a large number of target files are expected
|
| 312 |
+
(because no metadata is written to disc). Only "simplecache" is guaranteed thread/process-safe.
|
| 313 |
+
Cached files can still be removed by age using their local modification times, for example
|
| 314 |
+
``fs.clear_expired_cache(expiry_time=7 * 24 * 60 * 60)``. This only changes the writable cache
|
| 315 |
+
location when multiple cache directories are configured.
|
| 316 |
+
|
| 317 |
+
With "filecache" and "simplecache", each file is downloaded to a temporary ``*.part`` file in the
|
| 318 |
+
cache directory and renamed into place once complete, so a partial download is never visible. The
|
| 319 |
+
temporary file is removed if the download fails, but not if the process is killed mid-download;
|
| 320 |
+
leftover ``*.part`` files are ignored by the cache and safe to delete.
|
| 321 |
+
|
| 322 |
+
Remote Write Caching
|
| 323 |
+
--------------------
|
| 324 |
+
|
| 325 |
+
You can cache files to local files to send to remote using the "simplecache" protocol.
|
| 326 |
+
The following example demonstrates how this might look
|
| 327 |
+
|
| 328 |
+
.. code-block:: python
|
| 329 |
+
|
| 330 |
+
with fsspec.open('simplecache::s3://mybucket/myfile', 'wb',
|
| 331 |
+
s3={"profile": "writer"}) as f:
|
| 332 |
+
f.write(b"some data")
|
| 333 |
+
|
| 334 |
+
This will open a local file for writing, and when this file is closed, it will be uploaded
|
| 335 |
+
to the target URL, in this case on S3. The file-like object ``f`` can be passed to any
|
| 336 |
+
library expecting to write to a file. Note that we pass parameters to ``S3FileSystem`` using
|
| 337 |
+
the key ``"s3"``, the same as the name of the protocol.
|
| 338 |
+
|
| 339 |
+
File Selector (GUI)
|
| 340 |
+
-------------------
|
| 341 |
+
|
| 342 |
+
The module ``fsspec.gui`` contains a graphical file selector interface. It is built
|
| 343 |
+
using `panel`_, which must be installed in order to use the GUI. Upon instantiation,
|
| 344 |
+
you can provide the initial URL location (which can be returned to with the "🏠" button),
|
| 345 |
+
arguments and filters.
|
| 346 |
+
|
| 347 |
+
.. _panel: https://panel.holoviz.org/
|
| 348 |
+
|
| 349 |
+
.. image:: img/gui.png
|
| 350 |
+
|
| 351 |
+
Clicking on a directory will descend into it, and selecting a file will mark it as
|
| 352 |
+
the output of the interface. You can select any of the known protocols, but should
|
| 353 |
+
provide any required arguments in the "kwargs" box (as a dictionary) and any
|
| 354 |
+
absolute URL location before clicking "⇨" to go to that location. If using file filters,
|
| 355 |
+
they will appear as a list of checkboxes; only those file-endings selected will be
|
| 356 |
+
shown (or if none are selected, all files are shown).
|
| 357 |
+
|
| 358 |
+
The interface provides the following outputs:
|
| 359 |
+
|
| 360 |
+
#. ``.urlpath``: the currently selected item (if any)
|
| 361 |
+
#. ``.storage_options``: the value of the kwargs box
|
| 362 |
+
#. ``.fs``: the current filesystem instance
|
| 363 |
+
#. ``.open_file()``: produces an ``OpenFile`` instance for the current selection
|
| 364 |
+
|
| 365 |
+
Configuration
|
| 366 |
+
-------------
|
| 367 |
+
|
| 368 |
+
You can set default keyword arguments to pass to any fsspec backend by editing
|
| 369 |
+
config files, providing environment variables, or editing the contents of
|
| 370 |
+
the dictionary ``fsspec.config.conf``.
|
| 371 |
+
|
| 372 |
+
Files are stored in the directory pointed to by ``FSSPEC_CONFIG_DIR``,
|
| 373 |
+
``~/.config/fsspec/`` by default. Set ``FSSPEC_CONFIG_DIR`` before importing
|
| 374 |
+
``fsspec`` to read configuration from a different directory. All \*.ini and
|
| 375 |
+
\*.json files will be loaded as UTF-8, parsed from their respective formats and fed into the config dict
|
| 376 |
+
at import time. For example, if there is a file "~/.config/fsspec/conf.json"
|
| 377 |
+
containing
|
| 378 |
+
|
| 379 |
+
.. code-block:: json
|
| 380 |
+
|
| 381 |
+
{"file": {"auto_mkdir": true}}
|
| 382 |
+
|
| 383 |
+
then any instance of the file system whose protocol is "file" (i.e.,
|
| 384 |
+
``LocalFileSystem``) with be passed the kwargs ``auto_mkdir=True``
|
| 385 |
+
**unless** the user supplies the kwarg themselves.
|
| 386 |
+
|
| 387 |
+
For instance:
|
| 388 |
+
|
| 389 |
+
.. code-block:: python
|
| 390 |
+
|
| 391 |
+
import fsspec
|
| 392 |
+
fs = fsspec.filesystem("file")
|
| 393 |
+
assert fs.auto_mkdir == True
|
| 394 |
+
fs = fsspec.filesystem("file", auto_mkdir=False)
|
| 395 |
+
assert fs.auto_mkdir == False
|
| 396 |
+
|
| 397 |
+
Obviously, you should only define default values that are appropriate for
|
| 398 |
+
a given file system implementation. INI files only support string values.
|
| 399 |
+
|
| 400 |
+
Alternatively, you can provide overrides with environment variables of the style
|
| 401 |
+
``FSSPEC_{protocol}=<json_dict_value>`` and
|
| 402 |
+
``FSSPEC_{protocol}_{kwargname}=<value>``. Values are parsed as JSON when
|
| 403 |
+
possible; otherwise they remain strings. For example, in a POSIX shell:
|
| 404 |
+
|
| 405 |
+
.. code-block:: sh
|
| 406 |
+
|
| 407 |
+
export FSSPEC_FILE='{"auto_mkdir": true}'
|
| 408 |
+
export FSSPEC_FILE_AUTO_MKDIR=false
|
| 409 |
+
|
| 410 |
+
The per-option variable overrides the protocol dictionary, so this sets
|
| 411 |
+
``auto_mkdir`` to the boolean ``False``, not the string ``"false"``. Set these
|
| 412 |
+
variables before importing ``fsspec`` too.
|
| 413 |
+
|
| 414 |
+
Configuration is determined in the following order, with later items winning:
|
| 415 |
+
|
| 416 |
+
#. ini and json files in the config directory (``FSSPEC_CONFIG_DIR`` or ``$HOME/.config/fsspec/``), sorted
|
| 417 |
+
lexically by filename
|
| 418 |
+
#. ``FSSPEC_{protocol}`` environment variables
|
| 419 |
+
#. ``FSSPEC_{protocol}_{kwargname}`` environment variables
|
| 420 |
+
#. the contents of ``fsspec.config.conf``, which can be edited at runtime
|
| 421 |
+
#. kwargs explicitly passed, whether with ``fsspec.open``, ``fsspec.filesystem``
|
| 422 |
+
or directly instantiating the implementation class.
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
Asynchronous
|
| 426 |
+
------------
|
| 427 |
+
|
| 428 |
+
Some implementations, those deriving from ``fsspec.asyn.AsyncFileSystem``, have
|
| 429 |
+
async/coroutine implementations of some file operations. The async methods have
|
| 430 |
+
names beginning with ``_``, and listed in the ``asyn`` module; synchronous or
|
| 431 |
+
blocking functions are automatically generated, which will operate via an
|
| 432 |
+
event loop in another thread, by default.
|
| 433 |
+
|
| 434 |
+
See :doc:`async` for modes of operation and how to implement such file systems.
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
Callbacks
|
| 438 |
+
---------
|
| 439 |
+
|
| 440 |
+
Some methods support a ``callback=`` argument, which is the entry point to
|
| 441 |
+
providing feedback on transfers to the user or any other logging service. This
|
| 442 |
+
feature is new and experimental and supported by varying amounts in the
|
| 443 |
+
backends.
|
| 444 |
+
|
| 445 |
+
See the docstrings in the callbacks module for further details.
|
| 446 |
+
``fsspec.callbacks.TqdmCallback`` can be used to display a progress bar using
|
| 447 |
+
tqdm.
|
| 448 |
+
|
| 449 |
+
.. raw:: html
|
| 450 |
+
|
| 451 |
+
<script data-goatcounter="https://fsspec.goatcounter.com/count"
|
| 452 |
+
async src="//gc.zgo.at/count.js"></script>
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
Exclusive write
|
| 456 |
+
---------------
|
| 457 |
+
|
| 458 |
+
Some backends support writing to a file only if it doesn't already exist. This may be
|
| 459 |
+
implemented for the following methods:
|
| 460 |
+
- pipe_file (with argument ``mode=='create'``)
|
| 461 |
+
- put_file (with argument ``mode=='create'``)
|
| 462 |
+
- open (with argument ``mode="xb"``)
|
| 463 |
+
Since some writes will be achieved in blocks, the timing of when the check is done is
|
| 464 |
+
not defined - it may be at the start or at the completion of the operation, depending
|
| 465 |
+
on the backend.
|
| 466 |
+
|
| 467 |
+
If using exclusive mode on a file that does already exist, a ``FileExistsError`` will
|
| 468 |
+
be raised.
|
| 469 |
+
|
| 470 |
+
This feature is currently included on a trial basis and may change in the future.
|
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/img/gui.png
ADDED
|
Git LFS Details
|
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/index.rst
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
``fsspec``: Filesystem interfaces for Python
|
| 2 |
+
============================================
|
| 3 |
+
|
| 4 |
+
Filesystem Spec (``fsspec``) is a project to provide a unified pythonic interface to
|
| 5 |
+
local, remote and embedded file systems and bytes storage.
|
| 6 |
+
|
| 7 |
+
Brief Overview
|
| 8 |
+
--------------
|
| 9 |
+
|
| 10 |
+
There are many places to store bytes, from in memory, to the local disk, cluster
|
| 11 |
+
distributed storage, to the cloud. Many files also contain internal mappings of names to bytes,
|
| 12 |
+
maybe in a hierarchical directory-oriented tree. Working with all these different
|
| 13 |
+
storage media, and their associated libraries, is a pain. ``fsspec`` exists to
|
| 14 |
+
provide a familiar API that will work the same whatever the storage backend.
|
| 15 |
+
As much as possible, we iron out the quirks specific to each implementation,
|
| 16 |
+
so you need do no more than provide credentials for each service you access
|
| 17 |
+
(if needed) and thereafter not have to worry about the implementation again.
|
| 18 |
+
|
| 19 |
+
Why
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
``fsspec`` provides two main concepts: a set of filesystem classes with uniform APIs
|
| 23 |
+
(i.e., functions such as ``cp``, ``rm``, ``cat``, ``mkdir``, ...) supplying operations on a range of
|
| 24 |
+
storage systems; and top-level convenience functions like :func:`fsspec.open`, to allow
|
| 25 |
+
you to quickly get from a URL to a file-like object that you can use with a third-party
|
| 26 |
+
library or your own code.
|
| 27 |
+
|
| 28 |
+
The section :doc:`intro` gives motivation and history of this project, but
|
| 29 |
+
most users will want to skip straight to :doc:`usage` to find out how to use
|
| 30 |
+
the package and :doc:`features` to see the long list of added functionality
|
| 31 |
+
included along with the basic file-system interface.
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
Who uses ``fsspec``?
|
| 35 |
+
--------------------
|
| 36 |
+
|
| 37 |
+
You can use ``fsspec``'s file objects with any python function that accepts
|
| 38 |
+
file objects, because of *duck typing*.
|
| 39 |
+
|
| 40 |
+
You may well be using ``fsspec`` already without knowing it.
|
| 41 |
+
The following libraries use ``fsspec`` internally for path and file handling:
|
| 42 |
+
|
| 43 |
+
#. `Dask`_, the parallel, out-of-core and distributed
|
| 44 |
+
programming platform
|
| 45 |
+
#. `Intake`_, the data source cataloguing and loading
|
| 46 |
+
library and its plugins
|
| 47 |
+
#. `pandas`_, the tabular data analysis package
|
| 48 |
+
#. `xarray`_ and `zarr`_, multidimensional array
|
| 49 |
+
storage and labelled operations
|
| 50 |
+
#. `DVC`_, version control system
|
| 51 |
+
for machine learning projects
|
| 52 |
+
#. `Kedro`_, a Python framework for reproducible,
|
| 53 |
+
maintainable and modular data science code
|
| 54 |
+
#. `Huggingface🤗 Datasets`_, a popular library to
|
| 55 |
+
load&manipulate data for Deep Learning models
|
| 56 |
+
|
| 57 |
+
``fsspec`` filesystems are also supported by:
|
| 58 |
+
|
| 59 |
+
#. `pyarrow`_, the in-memory data layout engine
|
| 60 |
+
#. `petl`_, a general purpose package for extracting, transforming and loading tables of data.
|
| 61 |
+
|
| 62 |
+
... plus many more that we don't know about.
|
| 63 |
+
|
| 64 |
+
.. _Dask: https://dask.org/
|
| 65 |
+
.. _Intake: https://intake.readthedocs.io/
|
| 66 |
+
.. _pandas: https://pandas.pydata.org/
|
| 67 |
+
.. _xarray: https://docs.xarray.dev/
|
| 68 |
+
.. _zarr: https://zarr.readthedocs.io/
|
| 69 |
+
.. _DVC: https://dvc.org/
|
| 70 |
+
.. _kedro: https://docs.kedro.org/en/stable/tutorial/set_up_data.html#supported-data-locations
|
| 71 |
+
.. _pyxet: https://github.com/xetdata/pyxet
|
| 72 |
+
.. _Huggingface🤗 Datasets: https://github.com/huggingface/datasets
|
| 73 |
+
.. _pyarrow: https://arrow.apache.org/docs/python/
|
| 74 |
+
.. _petl: https://petl.readthedocs.io/en/stable/io.html#petl.io.remotes.RemoteSource
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
Installation
|
| 78 |
+
------------
|
| 79 |
+
|
| 80 |
+
``fsspec`` can be installed from PyPI or conda and has no dependencies of its own
|
| 81 |
+
|
| 82 |
+
.. code-block:: sh
|
| 83 |
+
|
| 84 |
+
pip install fsspec
|
| 85 |
+
conda install -c conda-forge fsspec
|
| 86 |
+
|
| 87 |
+
Not all filesystem implementations are available without installing extra
|
| 88 |
+
dependencies. For example to be able to access data in GCS, you can use the optional
|
| 89 |
+
pip install syntax below, or install the specific package required
|
| 90 |
+
|
| 91 |
+
.. code-block:: sh
|
| 92 |
+
|
| 93 |
+
pip install fsspec[gcs]
|
| 94 |
+
conda install -c conda-forge gcsfs
|
| 95 |
+
|
| 96 |
+
``fsspec`` attempts to provide the right message when you attempt to use a filesystem
|
| 97 |
+
for which you need additional dependencies.
|
| 98 |
+
The current list of known implementations can be found as follows
|
| 99 |
+
|
| 100 |
+
.. code-block:: python
|
| 101 |
+
|
| 102 |
+
from fsspec.registry import known_implementations
|
| 103 |
+
|
| 104 |
+
known_implementations
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
.. toctree::
|
| 109 |
+
:maxdepth: 1
|
| 110 |
+
:caption: Contents:
|
| 111 |
+
|
| 112 |
+
intro.rst
|
| 113 |
+
usage.rst
|
| 114 |
+
features.rst
|
| 115 |
+
copying.rst
|
| 116 |
+
developer.rst
|
| 117 |
+
async.rst
|
| 118 |
+
api.rst
|
| 119 |
+
changelog.rst
|
| 120 |
+
code-of-conduct.rst
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
These docs pages collect anonymous tracking data using goatcounter, and the
|
| 124 |
+
dashboard is available to the public: https://fsspec.goatcounter.com/ .
|
| 125 |
+
|
| 126 |
+
.. raw:: html
|
| 127 |
+
|
| 128 |
+
<script data-goatcounter="https://fsspec.goatcounter.com/count"
|
| 129 |
+
async src="//gc.zgo.at/count.js"></script>
|
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/intro.rst
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Background
|
| 2 |
+
==========
|
| 3 |
+
|
| 4 |
+
Python provides a standard interface for open files, so that alternate implementations of file-like object can
|
| 5 |
+
work seamlessly with many function which rely only on the methods of that standard interface. A number of libraries
|
| 6 |
+
have implemented a similar concept for file-systems, where file operations can be performed on a logical file-system
|
| 7 |
+
which may be local, structured data store or some remote service.
|
| 8 |
+
|
| 9 |
+
This repository is intended to be a place to define a standard interface that such file-systems should adhere to,
|
| 10 |
+
such that code using them should not have to know the details of the implementation in order to operate on any of
|
| 11 |
+
a number of backends. With hope, the community can come together to
|
| 12 |
+
define an interface that is the best for the highest number of users, and having the specification, makes developing
|
| 13 |
+
other file-system implementations simpler.
|
| 14 |
+
|
| 15 |
+
History
|
| 16 |
+
-------
|
| 17 |
+
|
| 18 |
+
We have been involved in building a number of remote-data file-system implementations, principally
|
| 19 |
+
in the context of the `Dask`_ project. In particular, several are listed
|
| 20 |
+
in `docs`_ with links to the specific repositories.
|
| 21 |
+
With common authorship, there is much that is similar between the implementations, for example posix-like naming
|
| 22 |
+
of the operations, and this has allowed Dask to be able to interact with the various backends and parse generic
|
| 23 |
+
URLs in order to select amongst them. However, *some* extra code was required in each case to adapt the peculiarities
|
| 24 |
+
of each implementation with the generic usage that Dask demanded. People may find the
|
| 25 |
+
`code`_ which parses URLs and creates file-system
|
| 26 |
+
instances interesting.
|
| 27 |
+
|
| 28 |
+
.. _Dask: https://dask.pydata.org/en/latest/
|
| 29 |
+
.. _docs: https://dask.pydata.org/en/latest/how-to/connect-to-remote-data.html
|
| 30 |
+
.. _code: https://github.com/fsspec/filesystem_spec/blob/4f0eb48/fsspec/core.py#L525
|
| 31 |
+
|
| 32 |
+
At the same time, the Apache `Arrow`_ project was also concerned with a similar problem,
|
| 33 |
+
particularly a common interface to local and HDFS files, for example the
|
| 34 |
+
`hdfs`_ interface (which actually communicated with HDFS
|
| 35 |
+
with a choice of driver). These are mostly used internally within Arrow, but Dask was modified in order to be able
|
| 36 |
+
to use the alternate HDFS interface (which solves some security issues with ``hdfs3``). In the process, a
|
| 37 |
+
`conversation`_
|
| 38 |
+
was started, and I invite all interested parties to continue the conversation in this location.
|
| 39 |
+
|
| 40 |
+
.. _Arrow: https://arrow.apache.org/
|
| 41 |
+
.. _hdfs: https://arrow.apache.org/docs/python/filesystems.html
|
| 42 |
+
.. _conversation: https://github.com/dask/dask/issues/2880
|
| 43 |
+
|
| 44 |
+
There is a good argument that this type of code has no place in Dask, which is concerned with making graphs
|
| 45 |
+
representing computations, and executing those graphs on a scheduler. Indeed, the file-systems are generally useful,
|
| 46 |
+
and each has a user-base wider than just those that work via Dask.
|
| 47 |
+
|
| 48 |
+
Influences
|
| 49 |
+
----------
|
| 50 |
+
|
| 51 |
+
The following places to consider, when choosing the definitions of how we would like the file-system specification
|
| 52 |
+
to look:
|
| 53 |
+
|
| 54 |
+
#. python's `os`_ module and its `path`_ namespace; also other file-connected
|
| 55 |
+
functionality in the standard library
|
| 56 |
+
#. posix/bash method naming conventions that linux/unix/osx users are familiar with; or perhaps their Windows variants
|
| 57 |
+
#. the existing implementations for the various backends (e.g.,
|
| 58 |
+
`gcsfs`_ or Arrow's
|
| 59 |
+
`hdfs`_)
|
| 60 |
+
#. `pyfilesystems`_, an attempt to do something similar, with a
|
| 61 |
+
plugin architecture. This conception has several types of local file-system, and a lot of well-thought-out
|
| 62 |
+
validation code.
|
| 63 |
+
|
| 64 |
+
.. _os: https://docs.python.org/3/library/os.html
|
| 65 |
+
.. _path: https://docs.python.org/3/library/os.path.html
|
| 66 |
+
.. _gcsfs: https://gcsfs.readthedocs.io/en/latest/api.html#gcsfs.core.GCSFileSystem
|
| 67 |
+
.. _pyfilesystems: https://docs.pyfilesystem.org/en/latest/index.html
|
| 68 |
+
|
| 69 |
+
Other similar work
|
| 70 |
+
------------------
|
| 71 |
+
|
| 72 |
+
It might have been conceivable to reuse code in ``pyfilesystems``, which has an established interface and several
|
| 73 |
+
implementations of its own. However, it supports none of the **critical** features for
|
| 74 |
+
cloud and parallel access, and would not be easy to
|
| 75 |
+
coerce. Following on the success of ``s3fs`` and ``gcsfs``, and their use within Dask, it seemed best to
|
| 76 |
+
have an interface as close to those as possible. See a
|
| 77 |
+
`discussion`_ on the topic.
|
| 78 |
+
|
| 79 |
+
.. _discussion: https://github.com/fsspec/filesystem_spec/issues/5
|
| 80 |
+
|
| 81 |
+
Other newer technologies such as `smart_open`_ and ``pyarrow``'s newer file-system rewrite also have some
|
| 82 |
+
parts of the functionality presented here, that might suit some use cases better.
|
| 83 |
+
|
| 84 |
+
.. _smart_open: https://github.com/RaRe-Technologies/smart_open
|
| 85 |
+
|
| 86 |
+
Structure of the package
|
| 87 |
+
------------------------
|
| 88 |
+
|
| 89 |
+
The best place to get a feel for the contents of ``fsspec`` is by looking through the :doc:`usage` and
|
| 90 |
+
:doc:`api` sections. In addition, the source code will be interesting for those who wish to subclass and
|
| 91 |
+
develop new file-system implementations. ``fsspec/spec.py`` contains the main abstract file-system class
|
| 92 |
+
to derive from, ``AbstractFileSystem``.
|
| 93 |
+
|
| 94 |
+
.. _zarr: https://zarr.readthedocs.io
|
| 95 |
+
|
| 96 |
+
.. raw:: html
|
| 97 |
+
|
| 98 |
+
<script data-goatcounter="https://fsspec.goatcounter.com/count"
|
| 99 |
+
async src="//gc.zgo.at/count.js"></script>
|
tasks/tasksmith-3bb3c78392c6/tests/source/docs/source/usage.rst
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Usage
|
| 2 |
+
=====
|
| 3 |
+
|
| 4 |
+
This is quick-start documentation to help people get familiar with the layout and functioning of ``fsspec``.
|
| 5 |
+
|
| 6 |
+
Instantiate a file-system
|
| 7 |
+
-------------------------
|
| 8 |
+
|
| 9 |
+
``fsspec`` provides an abstract file-system interface as a base class, to be used by other filesystems.
|
| 10 |
+
A file-system instance is an object for manipulating files on some
|
| 11 |
+
remote store, local files, files within some wrapper, or anything else that is capable of producing
|
| 12 |
+
file-like objects.
|
| 13 |
+
|
| 14 |
+
Some concrete implementations are bundled with ``fsspec`` and others can be installed separately. They
|
| 15 |
+
can be instantiated directly, or the ``registry`` can be used to find them.
|
| 16 |
+
|
| 17 |
+
Direct instantiation using the name of the class such as ``LocalFileSystem``, ``ZipFileSystem`` or
|
| 18 |
+
``S3FileSystem``:
|
| 19 |
+
|
| 20 |
+
.. code-block:: python
|
| 21 |
+
|
| 22 |
+
from fsspec.implementations.local import LocalFileSystem
|
| 23 |
+
|
| 24 |
+
fs = LocalFileSystem()
|
| 25 |
+
|
| 26 |
+
Look-up via registry:
|
| 27 |
+
|
| 28 |
+
.. code-block:: python
|
| 29 |
+
|
| 30 |
+
import fsspec
|
| 31 |
+
|
| 32 |
+
fs = fsspec.filesystem('file')
|
| 33 |
+
|
| 34 |
+
The argument passed here is the protocol name which maps across to the corresponding implementation
|
| 35 |
+
class ``LocalFileSystem``. Other examples are ``zip`` which maps across to ``ZipFileSystem`` and
|
| 36 |
+
``s3`` which maps across to ``S3FileSystem``.
|
| 37 |
+
|
| 38 |
+
Many filesystems also take extra parameters, some of which may be options - see :doc:`api`, or use
|
| 39 |
+
:func:`fsspec.get_filesystem_class` to get the class object and inspect its docstring.
|
| 40 |
+
|
| 41 |
+
.. code-block:: python
|
| 42 |
+
|
| 43 |
+
import fsspec
|
| 44 |
+
|
| 45 |
+
fs = fsspec.filesystem('ftp', host=host, port=port, username=user, password=pw)
|
| 46 |
+
|
| 47 |
+
The list of implemented ``fsspec`` protocols can be retrieved using :func:`fsspec.available_protocols`.
|
| 48 |
+
|
| 49 |
+
.. note::
|
| 50 |
+
|
| 51 |
+
The full list of the available protocols and the implementations that they map across to is
|
| 52 |
+
divided into two sections:
|
| 53 |
+
|
| 54 |
+
- Implementations built into ``fsspec``: :ref:`implementations`
|
| 55 |
+
- Implementations in separate packages: :ref:`external_implementations`
|
| 56 |
+
|
| 57 |
+
Use a file-system
|
| 58 |
+
-----------------
|
| 59 |
+
|
| 60 |
+
File-system instances offer a large number of methods for getting information about and manipulating files
|
| 61 |
+
for the given back-end. Although some specific implementations may not offer all features (e.g., ``http``
|
| 62 |
+
is read-only), generally all normal operations, such as ``ls``, ``rm``, should be expected to work (see the
|
| 63 |
+
full list: :class:`fsspec.spec.AbstractFileSystem`).
|
| 64 |
+
Note that this quick-start will prefer posix-style naming, but
|
| 65 |
+
many common operations are aliased: ``cp()`` and ``copy()`` are identical, for instance.
|
| 66 |
+
Functionality is generally chosen to be as close to the builtin ``os`` module's working for things like
|
| 67 |
+
``glob`` as possible. The following example uses an in-memory file-system, so it
|
| 68 |
+
can run without a remote service or credentials.
|
| 69 |
+
|
| 70 |
+
.. code-block:: python
|
| 71 |
+
|
| 72 |
+
import fsspec
|
| 73 |
+
|
| 74 |
+
fs = fsspec.filesystem("memory", global_store=False, skip_instance_cache=True)
|
| 75 |
+
fs.mkdir("/remote/output")
|
| 76 |
+
fs.touch("/remote/output/success") # creates empty file
|
| 77 |
+
assert fs.exists("/remote/output/success")
|
| 78 |
+
assert fs.isfile("/remote/output/success")
|
| 79 |
+
assert fs.cat("/remote/output/success") == b"" # get content as bytestring
|
| 80 |
+
fs.copy("/remote/output/success", "/remote/output/copy")
|
| 81 |
+
assert fs.ls("/remote/output", detail=False) == [
|
| 82 |
+
"/remote/output/copy",
|
| 83 |
+
"/remote/output/success",
|
| 84 |
+
]
|
| 85 |
+
fs.rm("/remote/output", recursive=True)
|
| 86 |
+
|
| 87 |
+
The ``open()`` method will return a file-like object which can be passed to any other library that expects
|
| 88 |
+
to work with python files, or used by your own code as you would a normal python file object.
|
| 89 |
+
These will normally be binary-mode only, but may implement internal buffering
|
| 90 |
+
in order to limit the number of reads from a remote source. They respect the use of ``with`` contexts. If
|
| 91 |
+
you have ``pandas`` installed, for example, you can do the following:
|
| 92 |
+
|
| 93 |
+
.. code-block:: python
|
| 94 |
+
|
| 95 |
+
f = fs.open("/remote/path/notes.txt", "rb")
|
| 96 |
+
lines = f.readline() # read to first b"\n"
|
| 97 |
+
f.seek(-10, 2)
|
| 98 |
+
foot = f.read() # read last 10 bytes of file
|
| 99 |
+
f.close()
|
| 100 |
+
|
| 101 |
+
import pandas as pd
|
| 102 |
+
with fs.open('/remote/data/myfile.csv') as f:
|
| 103 |
+
df = pd.read_csv(f, sep='|', header=None)
|
| 104 |
+
|
| 105 |
+
Higher-level
|
| 106 |
+
------------
|
| 107 |
+
|
| 108 |
+
For many situations, the only function that will be needed is :func:`fsspec.open_files()`, which will return
|
| 109 |
+
:class:`fsspec.core.OpenFile` instances created from a single URL and parameters to pass to the backend(s).
|
| 110 |
+
This supports text-mode and compression on the fly, and the objects can be serialized for passing between
|
| 111 |
+
processes or machines (so long as each has access to the same backend file-system). The protocol (i.e.,
|
| 112 |
+
backend) is inferred from the URL passed, and glob characters are expanded in read mode (search for files)
|
| 113 |
+
or write mode (create names). Critically, the file on the backend system is not actually opened until the
|
| 114 |
+
``OpenFile`` instance is used in a ``with`` context.
|
| 115 |
+
|
| 116 |
+
.. code-block:: python
|
| 117 |
+
|
| 118 |
+
of = fsspec.open("github://dask:fastparquet@main/test-data/nation.csv", "rt")
|
| 119 |
+
# of is an OpenFile container object. The "with" context below actually opens it
|
| 120 |
+
with of as f:
|
| 121 |
+
# now f is a text-mode file
|
| 122 |
+
for line in f:
|
| 123 |
+
# iterate text lines
|
| 124 |
+
print(line)
|
| 125 |
+
if "KENYA" in line:
|
| 126 |
+
break
|
| 127 |
+
|
| 128 |
+
Compressed files
|
| 129 |
+
----------------
|
| 130 |
+
|
| 131 |
+
Use the ``compression`` argument to :func:`fsspec.open` to read or write an
|
| 132 |
+
individual compressed file. This wraps the file object; it does not compress the
|
| 133 |
+
whole file-system. For example, write a gzip-compressed text file and read it back:
|
| 134 |
+
|
| 135 |
+
.. code-block:: python
|
| 136 |
+
|
| 137 |
+
import fsspec
|
| 138 |
+
|
| 139 |
+
with fsspec.open("example.txt.gz", "wt", compression="gzip", encoding="utf-8") as f:
|
| 140 |
+
f.write("Hello from fsspec!\n")
|
| 141 |
+
|
| 142 |
+
with fsspec.open("example.txt.gz", "rt", compression="infer", encoding="utf-8") as f:
|
| 143 |
+
assert f.read() == "Hello from fsspec!\n"
|
| 144 |
+
|
| 145 |
+
``compression="infer"`` selects a registered codec from the filename suffix,
|
| 146 |
+
such as ``.gz`` for gzip. Compression is not inferred by default:
|
| 147 |
+
``compression=None`` leaves the bytes unchanged, even if the filename ends in
|
| 148 |
+
``.gz``. The same ``compression`` argument is available on :func:`fsspec.open_files`.
|
| 149 |
+
|
| 150 |
+
Available codecs depend on your Python installation and optional packages.
|
| 151 |
+
Call :func:`fsspec.available_compressions` to see the codecs registered in the
|
| 152 |
+
current process. For example, ``"gzip"`` is a codec name, while ``None`` means no
|
| 153 |
+
compression.
|
| 154 |
+
|
| 155 |
+
For Zstandard (``compression="zstd"``, or ``compression="infer"`` with a ``.zst``
|
| 156 |
+
filename), fsspec first tries the standard-library ``compression.zstd`` module
|
| 157 |
+
on Python 3.14 and later. On older Python versions, install ``backports.zstd``:
|
| 158 |
+
|
| 159 |
+
.. code-block:: console
|
| 160 |
+
|
| 161 |
+
python -m pip install backports.zstd
|
| 162 |
+
|
| 163 |
+
If that backend is unavailable, fsspec also supports the ``zstandard`` package
|
| 164 |
+
as a fallback. Other optional codecs include ``lz4`` (install ``lz4``) and
|
| 165 |
+
``snappy`` (install ``python-snappy``). Install optional packages before importing
|
| 166 |
+
fsspec, or restart your Python process after installation so the codecs can be
|
| 167 |
+
registered.
|
| 168 |
+
|
| 169 |
+
Explicitly requesting an unavailable codec raises ``ValueError`` with a message
|
| 170 |
+
such as ``Compression type zstd not supported``. Inference only recognizes
|
| 171 |
+
suffixes registered by available codecs: if a suffix is not recognized,
|
| 172 |
+
``compression="infer"`` passes through the stored bytes without compression or
|
| 173 |
+
decompression. Use an explicit codec name
|
| 174 |
+
when you want a missing dependency to produce an error.
|
| 175 |
+
|
| 176 |
+
.. raw:: html
|
| 177 |
+
|
| 178 |
+
<script data-goatcounter="https://fsspec.goatcounter.com/count"
|
| 179 |
+
async src="//gc.zgo.at/count.js"></script>
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/__init__.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import caching
|
| 2 |
+
from .callbacks import Callback
|
| 3 |
+
from .compression import available_compressions
|
| 4 |
+
from .core import get_fs_token_paths, open, open_files, open_local, url_to_fs
|
| 5 |
+
from .exceptions import FSTimeoutError
|
| 6 |
+
from .mapping import FSMap, get_mapper
|
| 7 |
+
from .registry import (
|
| 8 |
+
available_protocols,
|
| 9 |
+
filesystem,
|
| 10 |
+
get_filesystem_class,
|
| 11 |
+
register_implementation,
|
| 12 |
+
registry,
|
| 13 |
+
)
|
| 14 |
+
from .spec import AbstractFileSystem
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
from ._version import __version__ # noqa: F401
|
| 18 |
+
except ImportError:
|
| 19 |
+
__version__ = "unknown"
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"AbstractFileSystem",
|
| 23 |
+
"FSTimeoutError",
|
| 24 |
+
"FSMap",
|
| 25 |
+
"filesystem",
|
| 26 |
+
"register_implementation",
|
| 27 |
+
"get_filesystem_class",
|
| 28 |
+
"get_fs_token_paths",
|
| 29 |
+
"get_mapper",
|
| 30 |
+
"open",
|
| 31 |
+
"open_files",
|
| 32 |
+
"open_local",
|
| 33 |
+
"registry",
|
| 34 |
+
"caching",
|
| 35 |
+
"Callback",
|
| 36 |
+
"available_protocols",
|
| 37 |
+
"available_compressions",
|
| 38 |
+
"url_to_fs",
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def process_entries():
|
| 43 |
+
try:
|
| 44 |
+
from importlib.metadata import entry_points
|
| 45 |
+
except ImportError:
|
| 46 |
+
return
|
| 47 |
+
if entry_points is not None:
|
| 48 |
+
try:
|
| 49 |
+
eps = entry_points()
|
| 50 |
+
except TypeError:
|
| 51 |
+
pass # importlib-metadata < 0.8
|
| 52 |
+
else:
|
| 53 |
+
if hasattr(eps, "select"): # Python 3.10+ / importlib_metadata >= 3.9.0
|
| 54 |
+
specs = eps.select(group="fsspec.specs")
|
| 55 |
+
else:
|
| 56 |
+
specs = eps.get("fsspec.specs", [])
|
| 57 |
+
registered_names = {}
|
| 58 |
+
for spec in specs:
|
| 59 |
+
err_msg = f"Unable to load filesystem from {spec}"
|
| 60 |
+
name = spec.name
|
| 61 |
+
if name in registered_names:
|
| 62 |
+
continue
|
| 63 |
+
registered_names[name] = True
|
| 64 |
+
register_implementation(
|
| 65 |
+
name,
|
| 66 |
+
spec.value.replace(":", "."),
|
| 67 |
+
errtxt=err_msg,
|
| 68 |
+
# We take our implementations as the ones to overload with if
|
| 69 |
+
# for some reason we encounter some, may be the same, already
|
| 70 |
+
# registered
|
| 71 |
+
clobber=True,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
process_entries()
|
tasks/tasksmith-3bb3c78392c6/tests/source/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 = '0.0.0'
|
| 22 |
+
__version_tuple__ = version_tuple = (0, 0, 0)
|
| 23 |
+
|
| 24 |
+
__commit_id__ = commit_id = None
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/archive.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 _not_a_file(self, path):
|
| 26 |
+
"""The error for opening ``path``, which is not a file member."""
|
| 27 |
+
return IsADirectoryError(path) if self.isdir(path) else FileNotFoundError(path)
|
| 28 |
+
|
| 29 |
+
def _all_dirnames(self, paths):
|
| 30 |
+
"""Returns *all* directory names for each path in paths, including intermediate
|
| 31 |
+
ones.
|
| 32 |
+
|
| 33 |
+
Parameters
|
| 34 |
+
----------
|
| 35 |
+
paths: Iterable of path strings
|
| 36 |
+
"""
|
| 37 |
+
if len(paths) == 0:
|
| 38 |
+
return set()
|
| 39 |
+
|
| 40 |
+
dirnames = {self._parent(path) for path in paths} - {self.root_marker}
|
| 41 |
+
return dirnames | self._all_dirnames(dirnames)
|
| 42 |
+
|
| 43 |
+
def info(self, path, **kwargs):
|
| 44 |
+
self._get_dirs()
|
| 45 |
+
path = self._strip_protocol(path)
|
| 46 |
+
if path in {"", "/"} and self.dir_cache:
|
| 47 |
+
return {"name": "", "type": "directory", "size": 0}
|
| 48 |
+
if path in self.dir_cache:
|
| 49 |
+
return self.dir_cache[path]
|
| 50 |
+
elif path + "/" in self.dir_cache:
|
| 51 |
+
return self.dir_cache[path + "/"]
|
| 52 |
+
else:
|
| 53 |
+
raise FileNotFoundError(path)
|
| 54 |
+
|
| 55 |
+
def ls(self, path, detail=True, **kwargs):
|
| 56 |
+
path = self._strip_protocol(path)
|
| 57 |
+
self._get_dirs()
|
| 58 |
+
paths = {}
|
| 59 |
+
for p, f in self.dir_cache.items():
|
| 60 |
+
p = p.rstrip("/")
|
| 61 |
+
if "/" in p:
|
| 62 |
+
root = p.rsplit("/", 1)[0]
|
| 63 |
+
else:
|
| 64 |
+
root = ""
|
| 65 |
+
if root == path.rstrip("/"):
|
| 66 |
+
paths[p] = f
|
| 67 |
+
elif all(
|
| 68 |
+
(a == b)
|
| 69 |
+
for a, b in zip(path.split("/"), [""] + p.strip("/").split("/"))
|
| 70 |
+
):
|
| 71 |
+
# root directory entry
|
| 72 |
+
ppath = p.rstrip("/").split("/", 1)[0]
|
| 73 |
+
if ppath not in paths:
|
| 74 |
+
out = {"name": ppath, "size": 0, "type": "directory"}
|
| 75 |
+
paths[ppath] = out
|
| 76 |
+
if not paths and path.strip("/"):
|
| 77 |
+
# Nothing is listed under ``path``, so it is a file, an empty
|
| 78 |
+
# directory or missing; ``info`` raises FileNotFoundError for the last.
|
| 79 |
+
info = self.info(path)
|
| 80 |
+
if info["type"] != "directory":
|
| 81 |
+
paths[info["name"]] = info
|
| 82 |
+
if detail:
|
| 83 |
+
out = sorted(paths.values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 4 |
+
import concurrent.futures
|
| 5 |
+
import functools
|
| 6 |
+
import inspect
|
| 7 |
+
import io
|
| 8 |
+
import logging
|
| 9 |
+
import numbers
|
| 10 |
+
import os
|
| 11 |
+
import re
|
| 12 |
+
import sys
|
| 13 |
+
import threading
|
| 14 |
+
from collections.abc import Iterable
|
| 15 |
+
from glob import has_magic
|
| 16 |
+
from typing import TYPE_CHECKING
|
| 17 |
+
|
| 18 |
+
from .callbacks import DEFAULT_CALLBACK
|
| 19 |
+
from .exceptions import FSTimeoutError
|
| 20 |
+
from .implementations.local import LocalFileSystem, make_path_posix, trailing_sep
|
| 21 |
+
from .spec import AbstractBufferedFile, AbstractFileSystem
|
| 22 |
+
from .utils import check_contained, glob_translate, is_exception, other_paths
|
| 23 |
+
|
| 24 |
+
private = re.compile("_[^_]")
|
| 25 |
+
iothread = [None] # dedicated fsspec IO thread
|
| 26 |
+
loop = [None] # global event loop for any non-async instance
|
| 27 |
+
_lock = threading.Lock()
|
| 28 |
+
get_running_loop = asyncio.get_running_loop
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_lock():
|
| 32 |
+
"""Return the process-local threading lock."""
|
| 33 |
+
return _lock
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def reset_lock():
|
| 37 |
+
"""Reset the global loop and lock after forking."""
|
| 38 |
+
global _lock
|
| 39 |
+
|
| 40 |
+
iothread[0] = None
|
| 41 |
+
loop[0] = None
|
| 42 |
+
_lock = threading.Lock()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
async def _runner(event, coro, result, timeout=None):
|
| 46 |
+
timeout = timeout if timeout else None # convert 0 or 0.0 to None
|
| 47 |
+
if timeout is not None:
|
| 48 |
+
coro = asyncio.wait_for(coro, timeout=timeout)
|
| 49 |
+
try:
|
| 50 |
+
result[0] = await coro
|
| 51 |
+
except Exception as ex:
|
| 52 |
+
result[0] = ex
|
| 53 |
+
finally:
|
| 54 |
+
event.set()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def sync(loop, func, *args, timeout=None, **kwargs):
|
| 58 |
+
"""
|
| 59 |
+
Make loop run coroutine until it returns. Runs in other thread
|
| 60 |
+
|
| 61 |
+
Examples
|
| 62 |
+
--------
|
| 63 |
+
>>> fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args,
|
| 64 |
+
timeout=timeout, **kwargs)
|
| 65 |
+
"""
|
| 66 |
+
timeout = timeout if timeout else None # convert 0 or 0.0 to None
|
| 67 |
+
# NB: if the loop is not running *yet*, it is OK to submit work
|
| 68 |
+
# and we will wait for it
|
| 69 |
+
if loop is None or loop.is_closed():
|
| 70 |
+
raise RuntimeError("Loop is not running")
|
| 71 |
+
if iothread[0] is not None and (
|
| 72 |
+
loop is globals()["loop"][0]
|
| 73 |
+
or (getattr(loop, "_thread_id", 0) or 0) == iothread[0].ident
|
| 74 |
+
):
|
| 75 |
+
if not iothread[0].is_alive():
|
| 76 |
+
raise RuntimeError("fsspec IO thread has already stopped.")
|
| 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 |
+
# the traceback of a stored exception includes _runner's frame, which holds
|
| 100 |
+
# ``result``: empty it so that frame does not refer back to the exception
|
| 101 |
+
result[0] = None
|
| 102 |
+
try:
|
| 103 |
+
if isinstance(return_result, asyncio.TimeoutError):
|
| 104 |
+
# suppress asyncio.TimeoutError, raise FSTimeoutError
|
| 105 |
+
raise FSTimeoutError from return_result
|
| 106 |
+
elif isinstance(return_result, BaseException):
|
| 107 |
+
raise return_result
|
| 108 |
+
else:
|
| 109 |
+
return return_result
|
| 110 |
+
finally:
|
| 111 |
+
# the traceback also includes this frame, so don't keep the exception
|
| 112 |
+
# in a local either: that would be a reference cycle
|
| 113 |
+
del return_result
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
_deferred_close_tasks = set()
|
| 117 |
+
_deferred_close_lock = threading.Lock()
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _on_loop_thread(loop):
|
| 121 |
+
"""Returns True if the current thread is servicing the given event loop."""
|
| 122 |
+
if loop is None:
|
| 123 |
+
return False
|
| 124 |
+
try:
|
| 125 |
+
return asyncio.get_running_loop() is loop
|
| 126 |
+
except RuntimeError:
|
| 127 |
+
return False
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _defer_task(
|
| 131 |
+
loop,
|
| 132 |
+
coro,
|
| 133 |
+
description="deferred task",
|
| 134 |
+
logger=None,
|
| 135 |
+
log_level=logging.WARNING,
|
| 136 |
+
):
|
| 137 |
+
"""Schedules a coroutine as a tracked background task on ``loop``.
|
| 138 |
+
|
| 139 |
+
Retains a strong reference in ``_deferred_close_tasks`` until completion to
|
| 140 |
+
prevent asyncio garbage collection from discarding pending tasks mid-flight,
|
| 141 |
+
and ensures unhandled task exceptions are retrieved and logged.
|
| 142 |
+
"""
|
| 143 |
+
task = loop.create_task(coro)
|
| 144 |
+
with _deferred_close_lock:
|
| 145 |
+
_deferred_close_tasks.add(task)
|
| 146 |
+
|
| 147 |
+
def _on_done(t):
|
| 148 |
+
with _deferred_close_lock:
|
| 149 |
+
_deferred_close_tasks.discard(t)
|
| 150 |
+
if not t.cancelled():
|
| 151 |
+
exc = t.exception()
|
| 152 |
+
if exc:
|
| 153 |
+
log = logger or logging.getLogger("fsspec.asyn")
|
| 154 |
+
log.log(
|
| 155 |
+
log_level,
|
| 156 |
+
"%s failed during asynchronous execution: %s",
|
| 157 |
+
description,
|
| 158 |
+
exc,
|
| 159 |
+
exc_info=exc,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
task.add_done_callback(_on_done)
|
| 163 |
+
return task
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def sync_teardown(
|
| 167 |
+
loop,
|
| 168 |
+
func_or_coro,
|
| 169 |
+
*args,
|
| 170 |
+
timeout=None,
|
| 171 |
+
description="teardown",
|
| 172 |
+
**kwargs,
|
| 173 |
+
):
|
| 174 |
+
"""Safely runs an async teardown coroutine on ``loop`` from synchronous context.
|
| 175 |
+
|
| 176 |
+
Schedules via :func:`asyncio.run_coroutine_threadsafe` or defers on the loop
|
| 177 |
+
thread to prevent deadlocks.
|
| 178 |
+
"""
|
| 179 |
+
coro = func_or_coro(*args, **kwargs) if callable(func_or_coro) else func_or_coro
|
| 180 |
+
if not asyncio.iscoroutine(coro):
|
| 181 |
+
return
|
| 182 |
+
|
| 183 |
+
if sys.is_finalizing():
|
| 184 |
+
coro.close()
|
| 185 |
+
return
|
| 186 |
+
|
| 187 |
+
if loop is None or not loop.is_running() or loop.is_closed():
|
| 188 |
+
coro.close()
|
| 189 |
+
raise RuntimeError(f"Skipping {description}: no usable IO loop available.")
|
| 190 |
+
|
| 191 |
+
if _on_loop_thread(loop):
|
| 192 |
+
_defer_task(loop, coro, description=description, log_level=logging.ERROR)
|
| 193 |
+
return
|
| 194 |
+
|
| 195 |
+
try:
|
| 196 |
+
future = asyncio.run_coroutine_threadsafe(coro, loop)
|
| 197 |
+
except RuntimeError:
|
| 198 |
+
coro.close()
|
| 199 |
+
raise RuntimeError(f"Skipping {description}: event loop is closed.") from None
|
| 200 |
+
|
| 201 |
+
if timeout is not None and timeout <= 0:
|
| 202 |
+
return
|
| 203 |
+
|
| 204 |
+
try:
|
| 205 |
+
return future.result(timeout)
|
| 206 |
+
except concurrent.futures.TimeoutError:
|
| 207 |
+
raise FSTimeoutError(
|
| 208 |
+
f"{description} did not complete within {timeout}s."
|
| 209 |
+
) from None
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def sync_wrapper(func, obj=None):
|
| 213 |
+
"""Given a function, make so can be called in blocking contexts
|
| 214 |
+
|
| 215 |
+
Leave obj=None if defining within a class. Pass the instance if attaching
|
| 216 |
+
as an attribute of the instance.
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
@functools.wraps(func)
|
| 220 |
+
def wrapper(*args, **kwargs):
|
| 221 |
+
self = obj or args[0]
|
| 222 |
+
return sync(self.loop, func, *args, **kwargs)
|
| 223 |
+
|
| 224 |
+
return wrapper
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def async_gen_wrapper(func, obj=None):
|
| 228 |
+
"""Given a async generator, make so can be called in blocking contexts"""
|
| 229 |
+
|
| 230 |
+
@functools.wraps(func)
|
| 231 |
+
def wrapper(*args, **kwargs):
|
| 232 |
+
self = obj or args[0]
|
| 233 |
+
gen = func(*args, **kwargs)
|
| 234 |
+
while True:
|
| 235 |
+
try:
|
| 236 |
+
yield sync(self.loop, gen.__anext__)
|
| 237 |
+
except StopAsyncIteration:
|
| 238 |
+
break
|
| 239 |
+
|
| 240 |
+
return wrapper
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def get_loop():
|
| 244 |
+
"""Create or return the default fsspec IO loop
|
| 245 |
+
|
| 246 |
+
The loop will be running on a separate thread.
|
| 247 |
+
"""
|
| 248 |
+
if loop[0] is None:
|
| 249 |
+
with get_lock():
|
| 250 |
+
# repeat the check just in case the loop got filled between the
|
| 251 |
+
# previous two calls from another thread
|
| 252 |
+
if loop[0] is None:
|
| 253 |
+
loop[0] = asyncio.new_event_loop()
|
| 254 |
+
th = threading.Thread(target=loop[0].run_forever, name="fsspecIO")
|
| 255 |
+
th.daemon = True
|
| 256 |
+
th.start()
|
| 257 |
+
iothread[0] = th
|
| 258 |
+
return loop[0]
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# How long to wait for the IO thread at exit before warning that it is stuck
|
| 262 |
+
_STOP_IO_LOOP_WARN_SECONDS = 1
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _stop_io_loop():
|
| 266 |
+
"""Stop the fsspec IO loop, if one was started, and wait for its thread.
|
| 267 |
+
|
| 268 |
+
The IO thread is a daemon, so nothing else stops it before interpreter
|
| 269 |
+
shutdown. It must not outlive ``Py_Finalize``: a callback firing on it
|
| 270 |
+
afterwards (for example a uvloop timer) re-enters the finalized interpreter
|
| 271 |
+
and crashes the process (#2241). atexit hooks run before finalization,
|
| 272 |
+
while the thread can still take the GIL to process the stop.
|
| 273 |
+
|
| 274 |
+
The stop takes effect once the running callback returns, so the wait only
|
| 275 |
+
lasts if a callback blocks the loop. That case is logged, then waited out:
|
| 276 |
+
letting the thread survive finalization would reintroduce the crash.
|
| 277 |
+
"""
|
| 278 |
+
if loop[0] is None or iothread[0] is None or not iothread[0].is_alive():
|
| 279 |
+
return
|
| 280 |
+
try:
|
| 281 |
+
loop[0].call_soon_threadsafe(loop[0].stop)
|
| 282 |
+
except RuntimeError:
|
| 283 |
+
# the loop was closed by its user
|
| 284 |
+
return
|
| 285 |
+
iothread[0].join(timeout=_STOP_IO_LOOP_WARN_SECONDS)
|
| 286 |
+
if iothread[0].is_alive():
|
| 287 |
+
logging.getLogger("fsspec.asyn").warning(
|
| 288 |
+
"fsspec IO loop is still running %ss after interpreter exit began; "
|
| 289 |
+
"a callback is blocking it. Waiting for it to finish.",
|
| 290 |
+
_STOP_IO_LOOP_WARN_SECONDS,
|
| 291 |
+
)
|
| 292 |
+
iothread[0].join()
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
# Registered at import, so it runs after any atexit hook registered later
|
| 296 |
+
# that may still use the loop. A forked child inherits this registration;
|
| 297 |
+
# the fork guard below clears ``loop``/``iothread`` there, so in the child it
|
| 298 |
+
# only stops a loop the child started itself, never the parent's thread.
|
| 299 |
+
atexit.register(_stop_io_loop)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def reset_after_fork():
|
| 303 |
+
reset_lock()
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
if hasattr(os, "register_at_fork"):
|
| 307 |
+
# should be posix; this will do nothing for spawn or forkserver subprocesses
|
| 308 |
+
os.register_at_fork(after_in_child=reset_after_fork)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
if TYPE_CHECKING:
|
| 312 |
+
import resource
|
| 313 |
+
|
| 314 |
+
ResourceError = resource.error
|
| 315 |
+
else:
|
| 316 |
+
try:
|
| 317 |
+
import resource
|
| 318 |
+
except ImportError:
|
| 319 |
+
resource = None
|
| 320 |
+
ResourceError = OSError
|
| 321 |
+
else:
|
| 322 |
+
ResourceError = getattr(resource, "error", OSError)
|
| 323 |
+
|
| 324 |
+
_DEFAULT_BATCH_SIZE = 128
|
| 325 |
+
_NOFILES_DEFAULT_BATCH_SIZE = 1280
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def _get_batch_size(nofiles=False):
|
| 329 |
+
from fsspec.config import conf
|
| 330 |
+
|
| 331 |
+
if nofiles:
|
| 332 |
+
if "nofiles_gather_batch_size" in conf:
|
| 333 |
+
return conf["nofiles_gather_batch_size"]
|
| 334 |
+
else:
|
| 335 |
+
if "gather_batch_size" in conf:
|
| 336 |
+
return conf["gather_batch_size"]
|
| 337 |
+
if nofiles:
|
| 338 |
+
return _NOFILES_DEFAULT_BATCH_SIZE
|
| 339 |
+
if resource is None:
|
| 340 |
+
return _DEFAULT_BATCH_SIZE
|
| 341 |
+
|
| 342 |
+
try:
|
| 343 |
+
soft_limit, _ = resource.getrlimit(resource.RLIMIT_NOFILE)
|
| 344 |
+
except (ImportError, ValueError, ResourceError):
|
| 345 |
+
return _DEFAULT_BATCH_SIZE
|
| 346 |
+
|
| 347 |
+
if soft_limit == resource.RLIM_INFINITY:
|
| 348 |
+
return -1
|
| 349 |
+
else:
|
| 350 |
+
return soft_limit // 8
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def running_async() -> bool:
|
| 354 |
+
"""Being executed by an event loop?"""
|
| 355 |
+
try:
|
| 356 |
+
asyncio.get_running_loop()
|
| 357 |
+
return True
|
| 358 |
+
except RuntimeError:
|
| 359 |
+
return False
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
async def _run_coros_in_chunks(
|
| 363 |
+
coros,
|
| 364 |
+
batch_size=None,
|
| 365 |
+
callback=DEFAULT_CALLBACK,
|
| 366 |
+
timeout=None,
|
| 367 |
+
return_exceptions=False,
|
| 368 |
+
nofiles=False,
|
| 369 |
+
):
|
| 370 |
+
"""Run the given coroutines in chunks.
|
| 371 |
+
|
| 372 |
+
Parameters
|
| 373 |
+
----------
|
| 374 |
+
coros: list of coroutines to run
|
| 375 |
+
batch_size: int or None
|
| 376 |
+
Number of coroutines to submit/wait on simultaneously.
|
| 377 |
+
If -1, then it will not be any throttling. If
|
| 378 |
+
None, it will be inferred from _get_batch_size()
|
| 379 |
+
callback: fsspec.callbacks.Callback instance
|
| 380 |
+
Gets a relative_update when each coroutine completes
|
| 381 |
+
timeout: number or None
|
| 382 |
+
If given, each coroutine times out after this time. Note that, since
|
| 383 |
+
there are multiple batches, the total run time of this function will in
|
| 384 |
+
general be longer
|
| 385 |
+
return_exceptions: bool
|
| 386 |
+
Same meaning as in asyncio.gather
|
| 387 |
+
nofiles: bool
|
| 388 |
+
If inferring the batch_size, does this operation involve local files?
|
| 389 |
+
If yes, you normally expect smaller batches.
|
| 390 |
+
"""
|
| 391 |
+
|
| 392 |
+
if batch_size is None:
|
| 393 |
+
batch_size = _get_batch_size(nofiles=nofiles)
|
| 394 |
+
|
| 395 |
+
if batch_size == -1:
|
| 396 |
+
batch_size = len(coros)
|
| 397 |
+
elif batch_size <= 0:
|
| 398 |
+
raise ValueError
|
| 399 |
+
|
| 400 |
+
async def _run_coro(coro, i):
|
| 401 |
+
try:
|
| 402 |
+
return await asyncio.wait_for(coro, timeout=timeout), i
|
| 403 |
+
except Exception as e:
|
| 404 |
+
if not return_exceptions:
|
| 405 |
+
raise
|
| 406 |
+
return e, i
|
| 407 |
+
finally:
|
| 408 |
+
callback.relative_update(1)
|
| 409 |
+
|
| 410 |
+
i = 0
|
| 411 |
+
n = len(coros)
|
| 412 |
+
results = [None] * n
|
| 413 |
+
pending = set()
|
| 414 |
+
|
| 415 |
+
while pending or i < n:
|
| 416 |
+
while len(pending) < batch_size and i < n:
|
| 417 |
+
pending.add(asyncio.ensure_future(_run_coro(coros[i], i)))
|
| 418 |
+
i += 1
|
| 419 |
+
|
| 420 |
+
if not pending:
|
| 421 |
+
break
|
| 422 |
+
|
| 423 |
+
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
|
| 424 |
+
first_exc = None
|
| 425 |
+
while done:
|
| 426 |
+
task = done.pop()
|
| 427 |
+
try:
|
| 428 |
+
result, k = await task
|
| 429 |
+
results[k] = result
|
| 430 |
+
except Exception as exc:
|
| 431 |
+
if first_exc is None:
|
| 432 |
+
first_exc = exc
|
| 433 |
+
|
| 434 |
+
if first_exc is not None:
|
| 435 |
+
for task in pending:
|
| 436 |
+
task.cancel()
|
| 437 |
+
if pending:
|
| 438 |
+
await asyncio.gather(*pending, return_exceptions=True)
|
| 439 |
+
try:
|
| 440 |
+
raise first_exc
|
| 441 |
+
finally:
|
| 442 |
+
# the traceback includes this frame, so it must not refer back
|
| 443 |
+
# to the exception: directly or through the finished task
|
| 444 |
+
del first_exc, task
|
| 445 |
+
|
| 446 |
+
return results
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
# these methods should be implemented as async by any async-able backend
|
| 450 |
+
async_methods = [
|
| 451 |
+
"_ls",
|
| 452 |
+
"_cat_file",
|
| 453 |
+
"_get_file",
|
| 454 |
+
"_put_file",
|
| 455 |
+
"_rm_file",
|
| 456 |
+
"_cp_file",
|
| 457 |
+
"_pipe_file",
|
| 458 |
+
"_expand_path",
|
| 459 |
+
"_info",
|
| 460 |
+
"_isfile",
|
| 461 |
+
"_isdir",
|
| 462 |
+
"_exists",
|
| 463 |
+
"_walk",
|
| 464 |
+
"_glob",
|
| 465 |
+
"_find",
|
| 466 |
+
"_du",
|
| 467 |
+
"_size",
|
| 468 |
+
"_mkdir",
|
| 469 |
+
"_makedirs",
|
| 470 |
+
]
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
class AsyncFileSystem(AbstractFileSystem):
|
| 474 |
+
"""Async file operations, default implementations
|
| 475 |
+
|
| 476 |
+
Passes bulk operations to asyncio.gather for concurrent operation.
|
| 477 |
+
|
| 478 |
+
Implementations that have concurrent batch operations and/or async methods
|
| 479 |
+
should inherit from this class instead of AbstractFileSystem. Docstrings are
|
| 480 |
+
copied from the un-underscored method in AbstractFileSystem, if not given.
|
| 481 |
+
"""
|
| 482 |
+
|
| 483 |
+
# note that methods do not have docstring here; they will be copied
|
| 484 |
+
# for _* methods and inferred for overridden methods.
|
| 485 |
+
|
| 486 |
+
async_impl = True
|
| 487 |
+
mirror_sync_methods = True
|
| 488 |
+
disable_throttling = False
|
| 489 |
+
|
| 490 |
+
def __init__(self, *args, asynchronous=False, loop=None, batch_size=None, **kwargs):
|
| 491 |
+
self.asynchronous = asynchronous
|
| 492 |
+
self._pid = os.getpid()
|
| 493 |
+
if not asynchronous:
|
| 494 |
+
self._loop = loop or get_loop()
|
| 495 |
+
else:
|
| 496 |
+
self._loop = None
|
| 497 |
+
self.batch_size = batch_size
|
| 498 |
+
super().__init__(*args, **kwargs)
|
| 499 |
+
|
| 500 |
+
@property
|
| 501 |
+
def loop(self):
|
| 502 |
+
if self._pid != os.getpid():
|
| 503 |
+
raise RuntimeError("This class is not fork-safe")
|
| 504 |
+
return self._loop
|
| 505 |
+
|
| 506 |
+
async def _rm_file(self, path, **kwargs):
|
| 507 |
+
if (
|
| 508 |
+
inspect.iscoroutinefunction(self._rm)
|
| 509 |
+
and type(self)._rm is not AsyncFileSystem._rm
|
| 510 |
+
):
|
| 511 |
+
return await self._rm(path, recursive=False, batch_size=1, **kwargs)
|
| 512 |
+
raise NotImplementedError
|
| 513 |
+
|
| 514 |
+
async def _rm(
|
| 515 |
+
self, path, recursive=False, batch_size=None, maxdepth=None, **kwargs
|
| 516 |
+
):
|
| 517 |
+
# TODO: implement on_error
|
| 518 |
+
batch_size = batch_size or self.batch_size
|
| 519 |
+
path = await self._expand_path(path, recursive=recursive, maxdepth=maxdepth)
|
| 520 |
+
return await _run_coros_in_chunks(
|
| 521 |
+
[self._rm_file(p, **kwargs) for p in reversed(path)],
|
| 522 |
+
batch_size=batch_size,
|
| 523 |
+
nofiles=True,
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
async def _cp_file(self, path1, path2, **kwargs):
|
| 527 |
+
raise NotImplementedError
|
| 528 |
+
|
| 529 |
+
async def _mv_file(self, path1, path2):
|
| 530 |
+
await self._cp_file(path1, path2)
|
| 531 |
+
await self._rm_file(path1)
|
| 532 |
+
|
| 533 |
+
async def _copy(
|
| 534 |
+
self,
|
| 535 |
+
path1,
|
| 536 |
+
path2,
|
| 537 |
+
recursive=False,
|
| 538 |
+
on_error=None,
|
| 539 |
+
maxdepth=None,
|
| 540 |
+
batch_size=None,
|
| 541 |
+
**kwargs,
|
| 542 |
+
):
|
| 543 |
+
if on_error is None and recursive:
|
| 544 |
+
on_error = "ignore"
|
| 545 |
+
elif on_error is None:
|
| 546 |
+
on_error = "raise"
|
| 547 |
+
|
| 548 |
+
if isinstance(path1, list) and isinstance(path2, list):
|
| 549 |
+
# No need to expand paths when both source and destination
|
| 550 |
+
# are provided as lists
|
| 551 |
+
paths1 = path1
|
| 552 |
+
paths2 = path2
|
| 553 |
+
else:
|
| 554 |
+
source_is_str = isinstance(path1, str)
|
| 555 |
+
paths1 = await self._expand_path(
|
| 556 |
+
path1, maxdepth=maxdepth, recursive=recursive
|
| 557 |
+
)
|
| 558 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 559 |
+
# Non-recursive glob does not copy directories
|
| 560 |
+
paths1 = [
|
| 561 |
+
p for p in paths1 if not (trailing_sep(p) or await self._isdir(p))
|
| 562 |
+
]
|
| 563 |
+
if not paths1:
|
| 564 |
+
return
|
| 565 |
+
|
| 566 |
+
source_is_file = len(paths1) == 1
|
| 567 |
+
dest_is_dir = isinstance(path2, str) and (
|
| 568 |
+
trailing_sep(path2) or await self._isdir(path2)
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
exists = source_is_str and (
|
| 572 |
+
(has_magic(path1) and source_is_file)
|
| 573 |
+
or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1))
|
| 574 |
+
)
|
| 575 |
+
paths2 = other_paths(
|
| 576 |
+
paths1,
|
| 577 |
+
path2,
|
| 578 |
+
exists=exists,
|
| 579 |
+
flatten=not source_is_str,
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
batch_size = batch_size or self.batch_size
|
| 583 |
+
coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)]
|
| 584 |
+
result = await _run_coros_in_chunks(
|
| 585 |
+
coros, batch_size=batch_size, return_exceptions=True, nofiles=True
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
for ex in filter(is_exception, result):
|
| 589 |
+
if on_error == "ignore" and isinstance(ex, FileNotFoundError):
|
| 590 |
+
continue
|
| 591 |
+
try:
|
| 592 |
+
raise ex
|
| 593 |
+
finally:
|
| 594 |
+
del ex, result
|
| 595 |
+
|
| 596 |
+
async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
|
| 597 |
+
raise NotImplementedError
|
| 598 |
+
|
| 599 |
+
async def _pipe(self, path, value=None, batch_size=None, **kwargs):
|
| 600 |
+
if isinstance(path, str):
|
| 601 |
+
path = {path: value}
|
| 602 |
+
batch_size = batch_size or self.batch_size
|
| 603 |
+
return await _run_coros_in_chunks(
|
| 604 |
+
[self._pipe_file(k, v, **kwargs) for k, v in path.items()],
|
| 605 |
+
batch_size=batch_size,
|
| 606 |
+
nofiles=True,
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
async def _process_limits(self, url, start, end):
|
| 610 |
+
"""Helper for "Range"-based _cat_file"""
|
| 611 |
+
size = None
|
| 612 |
+
suff = False
|
| 613 |
+
if start is not None and start < 0:
|
| 614 |
+
# if start is negative and end None, end is the "suffix length"
|
| 615 |
+
if end is None:
|
| 616 |
+
end = -start
|
| 617 |
+
start = ""
|
| 618 |
+
suff = True
|
| 619 |
+
else:
|
| 620 |
+
size = size or (await self._info(url))["size"]
|
| 621 |
+
start = size + start
|
| 622 |
+
elif start is None:
|
| 623 |
+
start = 0
|
| 624 |
+
if not suff:
|
| 625 |
+
if end is not None and end < 0:
|
| 626 |
+
if start is not None:
|
| 627 |
+
size = size or (await self._info(url))["size"]
|
| 628 |
+
end = size + end
|
| 629 |
+
elif end is None:
|
| 630 |
+
end = ""
|
| 631 |
+
if isinstance(end, numbers.Integral):
|
| 632 |
+
end -= 1 # bytes range is inclusive
|
| 633 |
+
return f"bytes={start}-{end}"
|
| 634 |
+
|
| 635 |
+
async def _cat_file(self, path, start=None, end=None, **kwargs):
|
| 636 |
+
raise NotImplementedError
|
| 637 |
+
|
| 638 |
+
async def _cat(
|
| 639 |
+
self, path, recursive=False, on_error="raise", batch_size=None, **kwargs
|
| 640 |
+
):
|
| 641 |
+
paths = await self._expand_path(path, recursive=recursive)
|
| 642 |
+
coros = [self._cat_file(path, **kwargs) for path in paths]
|
| 643 |
+
batch_size = batch_size or self.batch_size
|
| 644 |
+
out = await _run_coros_in_chunks(
|
| 645 |
+
coros, batch_size=batch_size, nofiles=True, return_exceptions=True
|
| 646 |
+
)
|
| 647 |
+
if on_error == "raise":
|
| 648 |
+
ex = next(filter(is_exception, out), False)
|
| 649 |
+
if ex:
|
| 650 |
+
try:
|
| 651 |
+
raise ex
|
| 652 |
+
finally:
|
| 653 |
+
del ex, out
|
| 654 |
+
if (
|
| 655 |
+
len(paths) > 1
|
| 656 |
+
or isinstance(path, list)
|
| 657 |
+
or paths[0] != self._strip_protocol(path)
|
| 658 |
+
):
|
| 659 |
+
return {
|
| 660 |
+
k: v
|
| 661 |
+
for k, v in zip(paths, out)
|
| 662 |
+
if on_error != "omit" or not is_exception(v)
|
| 663 |
+
}
|
| 664 |
+
else:
|
| 665 |
+
return out[0]
|
| 666 |
+
|
| 667 |
+
async def _cat_ranges(
|
| 668 |
+
self,
|
| 669 |
+
paths,
|
| 670 |
+
starts,
|
| 671 |
+
ends,
|
| 672 |
+
max_gap=None,
|
| 673 |
+
batch_size=None,
|
| 674 |
+
on_error="return",
|
| 675 |
+
**kwargs,
|
| 676 |
+
):
|
| 677 |
+
"""Get the contents of byte ranges from one or more files
|
| 678 |
+
|
| 679 |
+
Parameters
|
| 680 |
+
----------
|
| 681 |
+
paths: list
|
| 682 |
+
A list of of filepaths on this filesystems
|
| 683 |
+
starts, ends: int or list
|
| 684 |
+
Bytes limits of the read. If using a single int, the same value will be
|
| 685 |
+
used to read all the specified files.
|
| 686 |
+
on_error: "return" or "raise"
|
| 687 |
+
If "return" (default), any per-range exception is placed in the output
|
| 688 |
+
list at the corresponding position. Otherwise the first such exception
|
| 689 |
+
is raised. Matches ``AbstractFileSystem.cat_ranges``.
|
| 690 |
+
"""
|
| 691 |
+
if max_gap is not None:
|
| 692 |
+
# use utils.merge_offset_ranges
|
| 693 |
+
raise NotImplementedError
|
| 694 |
+
if not isinstance(paths, list):
|
| 695 |
+
raise TypeError
|
| 696 |
+
if not isinstance(starts, Iterable):
|
| 697 |
+
starts = [starts] * len(paths)
|
| 698 |
+
if not isinstance(ends, Iterable):
|
| 699 |
+
ends = [ends] * len(paths)
|
| 700 |
+
if len(starts) != len(paths) or len(ends) != len(paths):
|
| 701 |
+
raise ValueError
|
| 702 |
+
coros = [
|
| 703 |
+
self._cat_file(p, start=s, end=e, **kwargs)
|
| 704 |
+
for p, s, e in zip(paths, starts, ends)
|
| 705 |
+
]
|
| 706 |
+
batch_size = batch_size or self.batch_size
|
| 707 |
+
out = await _run_coros_in_chunks(
|
| 708 |
+
coros, batch_size=batch_size, nofiles=True, return_exceptions=True
|
| 709 |
+
)
|
| 710 |
+
if on_error != "return":
|
| 711 |
+
ex = next(filter(is_exception, out), None)
|
| 712 |
+
if ex is not None:
|
| 713 |
+
try:
|
| 714 |
+
raise ex
|
| 715 |
+
finally:
|
| 716 |
+
del ex, out
|
| 717 |
+
return out
|
| 718 |
+
|
| 719 |
+
async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
|
| 720 |
+
raise NotImplementedError
|
| 721 |
+
|
| 722 |
+
async def _put(
|
| 723 |
+
self,
|
| 724 |
+
lpath,
|
| 725 |
+
rpath,
|
| 726 |
+
recursive=False,
|
| 727 |
+
callback=DEFAULT_CALLBACK,
|
| 728 |
+
batch_size=None,
|
| 729 |
+
maxdepth=None,
|
| 730 |
+
**kwargs,
|
| 731 |
+
):
|
| 732 |
+
"""Copy file(s) from local.
|
| 733 |
+
|
| 734 |
+
Copies a specific file or tree of files (if recursive=True). If rpath
|
| 735 |
+
ends with a "/", it will be assumed to be a directory, and target files
|
| 736 |
+
will go within.
|
| 737 |
+
|
| 738 |
+
The put_file method will be called concurrently on a batch of files. The
|
| 739 |
+
batch_size option can configure the amount of futures that can be executed
|
| 740 |
+
at the same time. If it is -1, then all the files will be uploaded concurrently.
|
| 741 |
+
The default can be set for this instance by passing "batch_size" in the
|
| 742 |
+
constructor, or for all instances by setting the "gather_batch_size" key
|
| 743 |
+
in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
|
| 744 |
+
"""
|
| 745 |
+
if isinstance(lpath, list) and isinstance(rpath, list):
|
| 746 |
+
# No need to expand paths when both source and destination
|
| 747 |
+
# are provided as lists
|
| 748 |
+
rpaths = rpath
|
| 749 |
+
lpaths = lpath
|
| 750 |
+
else:
|
| 751 |
+
source_is_str = isinstance(lpath, str)
|
| 752 |
+
if source_is_str:
|
| 753 |
+
lpath = make_path_posix(lpath)
|
| 754 |
+
fs = LocalFileSystem()
|
| 755 |
+
lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth)
|
| 756 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 757 |
+
# Non-recursive glob does not copy directories
|
| 758 |
+
lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))]
|
| 759 |
+
if not lpaths:
|
| 760 |
+
return
|
| 761 |
+
|
| 762 |
+
source_is_file = len(lpaths) == 1
|
| 763 |
+
dest_is_dir = isinstance(rpath, str) and (
|
| 764 |
+
trailing_sep(rpath) or await self._isdir(rpath)
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
rpath = self._strip_protocol(rpath)
|
| 768 |
+
exists = source_is_str and (
|
| 769 |
+
(has_magic(lpath) and source_is_file)
|
| 770 |
+
or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath))
|
| 771 |
+
)
|
| 772 |
+
rpaths = other_paths(
|
| 773 |
+
lpaths,
|
| 774 |
+
rpath,
|
| 775 |
+
exists=exists,
|
| 776 |
+
flatten=not source_is_str,
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
is_dir = {l: os.path.isdir(l) for l in lpaths}
|
| 780 |
+
rdirs = [r for l, r in zip(lpaths, rpaths) if is_dir[l]]
|
| 781 |
+
file_pairs = [(l, r) for l, r in zip(lpaths, rpaths) if not is_dir[l]]
|
| 782 |
+
|
| 783 |
+
await asyncio.gather(*[self._makedirs(d, exist_ok=True) for d in rdirs])
|
| 784 |
+
batch_size = batch_size or self.batch_size
|
| 785 |
+
|
| 786 |
+
coros = []
|
| 787 |
+
callback.set_size(len(file_pairs))
|
| 788 |
+
for lfile, rfile in file_pairs:
|
| 789 |
+
put_file = callback.branch_coro(self._put_file)
|
| 790 |
+
coros.append(put_file(lfile, rfile, **kwargs))
|
| 791 |
+
|
| 792 |
+
return await _run_coros_in_chunks(
|
| 793 |
+
coros, batch_size=batch_size, callback=callback
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
async def _get_file(self, rpath, lpath, **kwargs):
|
| 797 |
+
raise NotImplementedError
|
| 798 |
+
|
| 799 |
+
async def _get(
|
| 800 |
+
self,
|
| 801 |
+
rpath,
|
| 802 |
+
lpath,
|
| 803 |
+
recursive=False,
|
| 804 |
+
callback=DEFAULT_CALLBACK,
|
| 805 |
+
maxdepth=None,
|
| 806 |
+
**kwargs,
|
| 807 |
+
):
|
| 808 |
+
"""Copy file(s) to local.
|
| 809 |
+
|
| 810 |
+
Copies a specific file or tree of files (if recursive=True). If lpath
|
| 811 |
+
ends with a "/", it will be assumed to be a directory, and target files
|
| 812 |
+
will go within. Can submit a list of paths, which may be glob-patterns
|
| 813 |
+
and will be expanded.
|
| 814 |
+
|
| 815 |
+
The get_file method will be called concurrently on a batch of files. The
|
| 816 |
+
batch_size option can configure the amount of futures that can be executed
|
| 817 |
+
at the same time. If it is -1, then all the files will be uploaded concurrently.
|
| 818 |
+
The default can be set for this instance by passing "batch_size" in the
|
| 819 |
+
constructor, or for all instances by setting the "gather_batch_size" key
|
| 820 |
+
in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
|
| 821 |
+
"""
|
| 822 |
+
if isinstance(lpath, list) and isinstance(rpath, list):
|
| 823 |
+
# No need to expand paths when both source and destination
|
| 824 |
+
# are provided as lists
|
| 825 |
+
rpaths = rpath
|
| 826 |
+
lpaths = lpath
|
| 827 |
+
else:
|
| 828 |
+
source_is_str = isinstance(rpath, str)
|
| 829 |
+
# First check for rpath trailing slash as _strip_protocol removes it.
|
| 830 |
+
source_not_trailing_sep = source_is_str and not trailing_sep(rpath)
|
| 831 |
+
rpath = self._strip_protocol(rpath)
|
| 832 |
+
rpaths = await self._expand_path(
|
| 833 |
+
rpath, recursive=recursive, maxdepth=maxdepth
|
| 834 |
+
)
|
| 835 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 836 |
+
# Non-recursive glob does not copy directories
|
| 837 |
+
rpaths = [
|
| 838 |
+
p for p in rpaths if not (trailing_sep(p) or await self._isdir(p))
|
| 839 |
+
]
|
| 840 |
+
if not rpaths:
|
| 841 |
+
return
|
| 842 |
+
|
| 843 |
+
lpath = make_path_posix(lpath)
|
| 844 |
+
source_is_file = len(rpaths) == 1
|
| 845 |
+
dest_is_dir = isinstance(lpath, str) and (
|
| 846 |
+
trailing_sep(lpath) or LocalFileSystem().isdir(lpath)
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
exists = source_is_str and (
|
| 850 |
+
(has_magic(rpath) and source_is_file)
|
| 851 |
+
or (not has_magic(rpath) and dest_is_dir and source_not_trailing_sep)
|
| 852 |
+
)
|
| 853 |
+
lpaths = other_paths(
|
| 854 |
+
rpaths,
|
| 855 |
+
lpath,
|
| 856 |
+
exists=exists,
|
| 857 |
+
flatten=not source_is_str,
|
| 858 |
+
)
|
| 859 |
+
if isinstance(lpath, str):
|
| 860 |
+
# The names came from the source listing; ".." in one of them
|
| 861 |
+
# would otherwise place the copy above the destination. When
|
| 862 |
+
# lpath is a list the caller named every destination itself.
|
| 863 |
+
check_contained(lpath, lpaths)
|
| 864 |
+
|
| 865 |
+
[os.makedirs(os.path.dirname(lp), exist_ok=True) for lp in lpaths]
|
| 866 |
+
batch_size = kwargs.pop("batch_size", self.batch_size)
|
| 867 |
+
|
| 868 |
+
coros = []
|
| 869 |
+
callback.set_size(len(lpaths))
|
| 870 |
+
for lpath, rpath in zip(lpaths, rpaths):
|
| 871 |
+
get_file = callback.branch_coro(self._get_file)
|
| 872 |
+
coros.append(get_file(rpath, lpath, **kwargs))
|
| 873 |
+
return await _run_coros_in_chunks(
|
| 874 |
+
coros, batch_size=batch_size, callback=callback
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
async def _isfile(self, path):
|
| 878 |
+
try:
|
| 879 |
+
return (await self._info(path))["type"] == "file"
|
| 880 |
+
except Exception:
|
| 881 |
+
return False
|
| 882 |
+
|
| 883 |
+
async def _isdir(self, path):
|
| 884 |
+
try:
|
| 885 |
+
return (await self._info(path))["type"] == "directory"
|
| 886 |
+
except OSError:
|
| 887 |
+
return False
|
| 888 |
+
|
| 889 |
+
async def _size(self, path):
|
| 890 |
+
return (await self._info(path)).get("size", None)
|
| 891 |
+
|
| 892 |
+
async def _sizes(self, paths, batch_size=None):
|
| 893 |
+
batch_size = batch_size or self.batch_size
|
| 894 |
+
return await _run_coros_in_chunks(
|
| 895 |
+
[self._size(p) for p in paths], batch_size=batch_size
|
| 896 |
+
)
|
| 897 |
+
|
| 898 |
+
async def _exists(self, path, **kwargs):
|
| 899 |
+
try:
|
| 900 |
+
await self._info(path, **kwargs)
|
| 901 |
+
return True
|
| 902 |
+
except FileNotFoundError:
|
| 903 |
+
return False
|
| 904 |
+
|
| 905 |
+
async def _info(self, path, **kwargs):
|
| 906 |
+
raise NotImplementedError
|
| 907 |
+
|
| 908 |
+
async def _ls(self, path, detail=True, **kwargs):
|
| 909 |
+
raise NotImplementedError
|
| 910 |
+
|
| 911 |
+
async def _walk(self, path, maxdepth=None, topdown=True, on_error="omit", **kwargs):
|
| 912 |
+
if maxdepth is not None and maxdepth < 1:
|
| 913 |
+
raise ValueError("maxdepth must be at least 1")
|
| 914 |
+
|
| 915 |
+
path = self._strip_protocol(path)
|
| 916 |
+
full_dirs = {}
|
| 917 |
+
dirs = {}
|
| 918 |
+
files = {}
|
| 919 |
+
|
| 920 |
+
detail = kwargs.pop("detail", False)
|
| 921 |
+
try:
|
| 922 |
+
listing = await self._ls(path, detail=True, **kwargs)
|
| 923 |
+
except (FileNotFoundError, OSError) as e:
|
| 924 |
+
if on_error == "raise":
|
| 925 |
+
raise
|
| 926 |
+
elif callable(on_error):
|
| 927 |
+
on_error(e)
|
| 928 |
+
if detail:
|
| 929 |
+
yield path, {}, {}
|
| 930 |
+
else:
|
| 931 |
+
yield path, [], []
|
| 932 |
+
return
|
| 933 |
+
|
| 934 |
+
for info in listing:
|
| 935 |
+
# each info name must be at least [path]/part , but here
|
| 936 |
+
# we check also for names like [path]/part/
|
| 937 |
+
pathname = info["name"].rstrip("/")
|
| 938 |
+
name = pathname.rsplit("/", 1)[-1]
|
| 939 |
+
if info["type"] == "directory" and pathname != path:
|
| 940 |
+
# do not include "self" path
|
| 941 |
+
full_dirs[name] = pathname
|
| 942 |
+
dirs[name] = info
|
| 943 |
+
elif pathname == path:
|
| 944 |
+
# file-like with same name as give path
|
| 945 |
+
files[""] = info
|
| 946 |
+
else:
|
| 947 |
+
files[name] = info
|
| 948 |
+
|
| 949 |
+
if not detail:
|
| 950 |
+
dirs = list(dirs)
|
| 951 |
+
files = list(files)
|
| 952 |
+
|
| 953 |
+
if topdown:
|
| 954 |
+
# Yield before recursion if walking top down
|
| 955 |
+
yield path, dirs, files
|
| 956 |
+
|
| 957 |
+
if maxdepth is not None:
|
| 958 |
+
maxdepth -= 1
|
| 959 |
+
if maxdepth < 1:
|
| 960 |
+
if not topdown:
|
| 961 |
+
yield path, dirs, files
|
| 962 |
+
return
|
| 963 |
+
|
| 964 |
+
for d in dirs:
|
| 965 |
+
async for _ in self._walk(
|
| 966 |
+
full_dirs[d],
|
| 967 |
+
maxdepth=maxdepth,
|
| 968 |
+
detail=detail,
|
| 969 |
+
topdown=topdown,
|
| 970 |
+
on_error=on_error,
|
| 971 |
+
**kwargs,
|
| 972 |
+
):
|
| 973 |
+
yield _
|
| 974 |
+
|
| 975 |
+
if not topdown:
|
| 976 |
+
# Yield after recursion if walking bottom up
|
| 977 |
+
yield path, dirs, files
|
| 978 |
+
|
| 979 |
+
async def _glob(self, path, maxdepth=None, **kwargs):
|
| 980 |
+
if maxdepth is not None and maxdepth < 1:
|
| 981 |
+
raise ValueError("maxdepth must be at least 1")
|
| 982 |
+
|
| 983 |
+
import re
|
| 984 |
+
|
| 985 |
+
seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
|
| 986 |
+
ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
|
| 987 |
+
path = self._strip_protocol(path)
|
| 988 |
+
append_slash_to_dirname = ends_with_sep or path.endswith(
|
| 989 |
+
tuple(sep + "**" for sep in seps)
|
| 990 |
+
)
|
| 991 |
+
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
|
| 992 |
+
idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
|
| 993 |
+
idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
|
| 994 |
+
|
| 995 |
+
min_idx = min(idx_star, idx_qmark, idx_brace)
|
| 996 |
+
|
| 997 |
+
detail = kwargs.pop("detail", False)
|
| 998 |
+
withdirs = kwargs.pop("withdirs", True)
|
| 999 |
+
|
| 1000 |
+
if not has_magic(path):
|
| 1001 |
+
if await self._exists(path, **kwargs):
|
| 1002 |
+
if not detail:
|
| 1003 |
+
return [path]
|
| 1004 |
+
else:
|
| 1005 |
+
return {path: await self._info(path, **kwargs)}
|
| 1006 |
+
else:
|
| 1007 |
+
if not detail:
|
| 1008 |
+
return [] # glob of non-existent returns empty
|
| 1009 |
+
else:
|
| 1010 |
+
return {}
|
| 1011 |
+
elif "/" in path[:min_idx]:
|
| 1012 |
+
first_wildcard_idx = min_idx
|
| 1013 |
+
min_idx = path[:min_idx].rindex("/")
|
| 1014 |
+
root = path[
|
| 1015 |
+
: min_idx + 1
|
| 1016 |
+
] # everything up to the last / before the first wildcard
|
| 1017 |
+
prefix = path[
|
| 1018 |
+
min_idx + 1 : first_wildcard_idx
|
| 1019 |
+
] # stem between last "/" and first wildcard
|
| 1020 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 1021 |
+
else:
|
| 1022 |
+
root = ""
|
| 1023 |
+
prefix = path[:min_idx] # stem up to the first wildcard
|
| 1024 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 1025 |
+
|
| 1026 |
+
if "**" in path:
|
| 1027 |
+
if maxdepth is not None:
|
| 1028 |
+
idx_double_stars = path.find("**")
|
| 1029 |
+
depth_double_stars = path[idx_double_stars:].count("/") + 1
|
| 1030 |
+
depth = depth - depth_double_stars + maxdepth
|
| 1031 |
+
else:
|
| 1032 |
+
depth = None
|
| 1033 |
+
|
| 1034 |
+
# Pass the filename stem as prefix= so backends that support it such as
|
| 1035 |
+
# gcsfs, s3fs and adlfs can filter server-side up to the first wildcard.
|
| 1036 |
+
if prefix:
|
| 1037 |
+
kwargs["prefix"] = prefix
|
| 1038 |
+
allpaths = await self._find(
|
| 1039 |
+
root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs
|
| 1040 |
+
)
|
| 1041 |
+
|
| 1042 |
+
pattern = glob_translate(path + ("/" if ends_with_sep else ""))
|
| 1043 |
+
pattern = re.compile(pattern)
|
| 1044 |
+
|
| 1045 |
+
out = {
|
| 1046 |
+
p: info
|
| 1047 |
+
for p, info in sorted(allpaths.items())
|
| 1048 |
+
if pattern.match(
|
| 1049 |
+
p + "/"
|
| 1050 |
+
if append_slash_to_dirname and info["type"] == "directory"
|
| 1051 |
+
else p
|
| 1052 |
+
)
|
| 1053 |
+
}
|
| 1054 |
+
|
| 1055 |
+
if detail:
|
| 1056 |
+
return out
|
| 1057 |
+
else:
|
| 1058 |
+
return list(out)
|
| 1059 |
+
|
| 1060 |
+
async def _du(self, path, total=True, maxdepth=None, **kwargs):
|
| 1061 |
+
sizes = {}
|
| 1062 |
+
# async for?
|
| 1063 |
+
for f in await self._find(path, maxdepth=maxdepth, **kwargs):
|
| 1064 |
+
info = await self._info(f)
|
| 1065 |
+
sizes[info["name"]] = info["size"]
|
| 1066 |
+
if total:
|
| 1067 |
+
return sum(sizes.values())
|
| 1068 |
+
else:
|
| 1069 |
+
return sizes
|
| 1070 |
+
|
| 1071 |
+
async def _find(self, path, maxdepth=None, withdirs=False, **kwargs):
|
| 1072 |
+
path = self._strip_protocol(path)
|
| 1073 |
+
out = {}
|
| 1074 |
+
detail = kwargs.pop("detail", False)
|
| 1075 |
+
|
| 1076 |
+
# Add the root directory if withdirs is requested
|
| 1077 |
+
# This is needed for posix glob compliance
|
| 1078 |
+
if withdirs and path != "" and await self._isdir(path):
|
| 1079 |
+
out[path] = await self._info(path)
|
| 1080 |
+
|
| 1081 |
+
# async for?
|
| 1082 |
+
async for _, dirs, files in self._walk(path, maxdepth, detail=True, **kwargs):
|
| 1083 |
+
if withdirs:
|
| 1084 |
+
files.update(dirs)
|
| 1085 |
+
out.update({info["name"]: info for name, info in files.items()})
|
| 1086 |
+
if not out and (await self._isfile(path)):
|
| 1087 |
+
# walk works on directories, but find should also return [path]
|
| 1088 |
+
# when path happens to be a file
|
| 1089 |
+
out[path] = {}
|
| 1090 |
+
names = sorted(out)
|
| 1091 |
+
if not detail:
|
| 1092 |
+
return names
|
| 1093 |
+
else:
|
| 1094 |
+
return {name: out[name] for name in names}
|
| 1095 |
+
|
| 1096 |
+
async def _expand_path(
|
| 1097 |
+
self, path, recursive=False, maxdepth=None, assume_literal=False
|
| 1098 |
+
):
|
| 1099 |
+
if maxdepth is not None and maxdepth < 1:
|
| 1100 |
+
raise ValueError("maxdepth must be at least 1")
|
| 1101 |
+
|
| 1102 |
+
if isinstance(path, str):
|
| 1103 |
+
out = await self._expand_path([path], recursive, maxdepth)
|
| 1104 |
+
else:
|
| 1105 |
+
out = set()
|
| 1106 |
+
path = [self._strip_protocol(p) for p in path]
|
| 1107 |
+
for p in path: # can gather here
|
| 1108 |
+
if not assume_literal and has_magic(p):
|
| 1109 |
+
bit = set(await self._glob(p, maxdepth=maxdepth))
|
| 1110 |
+
out |= bit
|
| 1111 |
+
if recursive:
|
| 1112 |
+
# glob call above expanded one depth so if maxdepth is defined
|
| 1113 |
+
# then decrement it in expand_path call below. If it is zero
|
| 1114 |
+
# after decrementing then avoid expand_path call.
|
| 1115 |
+
if maxdepth is not None and maxdepth <= 1:
|
| 1116 |
+
continue
|
| 1117 |
+
out |= set(
|
| 1118 |
+
await self._expand_path(
|
| 1119 |
+
list(bit),
|
| 1120 |
+
recursive=recursive,
|
| 1121 |
+
maxdepth=maxdepth - 1 if maxdepth is not None else None,
|
| 1122 |
+
assume_literal=True,
|
| 1123 |
+
)
|
| 1124 |
+
)
|
| 1125 |
+
continue
|
| 1126 |
+
elif recursive:
|
| 1127 |
+
rec = set(await self._find(p, maxdepth=maxdepth, withdirs=True))
|
| 1128 |
+
out |= rec
|
| 1129 |
+
if p not in out and (recursive is False or (await self._exists(p))):
|
| 1130 |
+
# should only check once, for the root
|
| 1131 |
+
out.add(p)
|
| 1132 |
+
if not out:
|
| 1133 |
+
raise FileNotFoundError(path)
|
| 1134 |
+
return sorted(out)
|
| 1135 |
+
|
| 1136 |
+
async def _mkdir(self, path, create_parents=True, **kwargs):
|
| 1137 |
+
pass # not necessary to implement, may not have directories
|
| 1138 |
+
|
| 1139 |
+
async def _makedirs(self, path, exist_ok=False):
|
| 1140 |
+
pass # not necessary to implement, may not have directories
|
| 1141 |
+
|
| 1142 |
+
async def open_async(self, path, mode="rb", **kwargs):
|
| 1143 |
+
if "b" not in mode or kwargs.get("compression"):
|
| 1144 |
+
raise ValueError
|
| 1145 |
+
raise NotImplementedError
|
| 1146 |
+
|
| 1147 |
+
|
| 1148 |
+
def mirror_sync_methods(obj):
|
| 1149 |
+
"""Populate sync and async methods for obj
|
| 1150 |
+
|
| 1151 |
+
For each method will create a sync version if the name refers to an async method
|
| 1152 |
+
(coroutine) and there is no override in the child class; will create an async
|
| 1153 |
+
method for the corresponding sync method if there is no implementation.
|
| 1154 |
+
|
| 1155 |
+
Uses the methods specified in
|
| 1156 |
+
- async_methods: the set that an implementation is expected to provide
|
| 1157 |
+
- default_async_methods: that can be derived from their sync version in
|
| 1158 |
+
AbstractFileSystem
|
| 1159 |
+
- AsyncFileSystem: async-specific default coroutines
|
| 1160 |
+
"""
|
| 1161 |
+
from fsspec import AbstractFileSystem
|
| 1162 |
+
|
| 1163 |
+
for method in set(async_methods + dir(AsyncFileSystem)):
|
| 1164 |
+
if not method.startswith("_"):
|
| 1165 |
+
continue
|
| 1166 |
+
smethod = method[1:]
|
| 1167 |
+
if private.match(method):
|
| 1168 |
+
isco = inspect.iscoroutinefunction(getattr(obj, method, None))
|
| 1169 |
+
unsync = getattr(getattr(obj, smethod, False), "__func__", None)
|
| 1170 |
+
is_default = unsync is getattr(AbstractFileSystem, smethod, "")
|
| 1171 |
+
if isco and is_default:
|
| 1172 |
+
mth = sync_wrapper(getattr(obj, method), obj=obj)
|
| 1173 |
+
elif inspect.isasyncgenfunction(getattr(obj, method, None)) and is_default:
|
| 1174 |
+
mth = async_gen_wrapper(getattr(obj, method), obj=obj)
|
| 1175 |
+
else:
|
| 1176 |
+
continue
|
| 1177 |
+
setattr(obj, smethod, mth)
|
| 1178 |
+
if not mth.__doc__:
|
| 1179 |
+
mth.__doc__ = getattr(
|
| 1180 |
+
getattr(AbstractFileSystem, smethod, None), "__doc__", ""
|
| 1181 |
+
)
|
| 1182 |
+
|
| 1183 |
+
|
| 1184 |
+
class FSSpecCoroutineCancel(Exception):
|
| 1185 |
+
pass
|
| 1186 |
+
|
| 1187 |
+
|
| 1188 |
+
def _dump_running_tasks(
|
| 1189 |
+
printout=True, cancel=True, exc=FSSpecCoroutineCancel, with_task=False
|
| 1190 |
+
):
|
| 1191 |
+
import traceback
|
| 1192 |
+
|
| 1193 |
+
tasks = [t for t in asyncio.tasks.all_tasks(loop[0]) if not t.done()]
|
| 1194 |
+
if printout:
|
| 1195 |
+
[task.print_stack() for task in tasks]
|
| 1196 |
+
out = [
|
| 1197 |
+
{
|
| 1198 |
+
"locals": task._coro.cr_frame.f_locals,
|
| 1199 |
+
"file": task._coro.cr_frame.f_code.co_filename,
|
| 1200 |
+
"firstline": task._coro.cr_frame.f_code.co_firstlineno,
|
| 1201 |
+
"linelo": task._coro.cr_frame.f_lineno,
|
| 1202 |
+
"stack": traceback.format_stack(task._coro.cr_frame),
|
| 1203 |
+
"task": task if with_task else None,
|
| 1204 |
+
}
|
| 1205 |
+
for task in tasks
|
| 1206 |
+
]
|
| 1207 |
+
if cancel:
|
| 1208 |
+
for t in tasks:
|
| 1209 |
+
cbs = t._callbacks
|
| 1210 |
+
t.cancel()
|
| 1211 |
+
asyncio.futures.Future.set_exception(t, exc)
|
| 1212 |
+
asyncio.futures.Future.cancel(t)
|
| 1213 |
+
[cb[0](t) for cb in cbs] # cancels any dependent concurrent.futures
|
| 1214 |
+
try:
|
| 1215 |
+
t._coro.throw(exc) # exits coro, unless explicitly handled
|
| 1216 |
+
except exc:
|
| 1217 |
+
pass
|
| 1218 |
+
return out
|
| 1219 |
+
|
| 1220 |
+
|
| 1221 |
+
class AbstractAsyncStreamedFile(AbstractBufferedFile):
|
| 1222 |
+
# no read buffering, and always auto-commit
|
| 1223 |
+
# TODO: readahead might still be useful here, but needs async version
|
| 1224 |
+
|
| 1225 |
+
async def read(self, length=-1):
|
| 1226 |
+
"""
|
| 1227 |
+
Return data from cache, or fetch pieces as necessary
|
| 1228 |
+
|
| 1229 |
+
Parameters
|
| 1230 |
+
----------
|
| 1231 |
+
length: int (-1)
|
| 1232 |
+
Number of bytes to read; if <0, all remaining bytes.
|
| 1233 |
+
"""
|
| 1234 |
+
length = -1 if length is None else int(length)
|
| 1235 |
+
if self.mode != "rb":
|
| 1236 |
+
raise ValueError("File not in read mode")
|
| 1237 |
+
if length < 0:
|
| 1238 |
+
length = self.size - self.loc
|
| 1239 |
+
if self.closed:
|
| 1240 |
+
raise ValueError("I/O operation on closed file.")
|
| 1241 |
+
if length == 0:
|
| 1242 |
+
# don't even bother calling fetch
|
| 1243 |
+
return b""
|
| 1244 |
+
out = await self._fetch_range(self.loc, self.loc + length)
|
| 1245 |
+
self.loc += len(out)
|
| 1246 |
+
return out
|
| 1247 |
+
|
| 1248 |
+
async def write(self, data):
|
| 1249 |
+
"""
|
| 1250 |
+
Write data to buffer.
|
| 1251 |
+
|
| 1252 |
+
Buffer only sent on flush() or if buffer is greater than
|
| 1253 |
+
or equal to blocksize.
|
| 1254 |
+
|
| 1255 |
+
Parameters
|
| 1256 |
+
----------
|
| 1257 |
+
data: bytes
|
| 1258 |
+
Set of bytes to be written.
|
| 1259 |
+
"""
|
| 1260 |
+
if self.mode not in {"wb", "ab"}:
|
| 1261 |
+
raise ValueError("File not in write mode")
|
| 1262 |
+
if self.closed:
|
| 1263 |
+
raise ValueError("I/O operation on closed file.")
|
| 1264 |
+
if self.forced:
|
| 1265 |
+
raise ValueError("This file has been force-flushed, can only close")
|
| 1266 |
+
out = self.buffer.write(data)
|
| 1267 |
+
self.loc += out
|
| 1268 |
+
if self.buffer.tell() >= self.blocksize:
|
| 1269 |
+
await self.flush()
|
| 1270 |
+
return out
|
| 1271 |
+
|
| 1272 |
+
async def close(self):
|
| 1273 |
+
"""Close file
|
| 1274 |
+
|
| 1275 |
+
Finalizes writes, discards cache
|
| 1276 |
+
"""
|
| 1277 |
+
if getattr(self, "_unclosable", False):
|
| 1278 |
+
return
|
| 1279 |
+
if self.closed:
|
| 1280 |
+
return
|
| 1281 |
+
if self.mode == "rb":
|
| 1282 |
+
self.cache = None
|
| 1283 |
+
else:
|
| 1284 |
+
if not self.forced:
|
| 1285 |
+
await self.flush(force=True)
|
| 1286 |
+
|
| 1287 |
+
if self.fs is not None:
|
| 1288 |
+
self.fs.invalidate_cache(self.path)
|
| 1289 |
+
self.fs.invalidate_cache(self.fs._parent(self.path))
|
| 1290 |
+
|
| 1291 |
+
self.closed = True
|
| 1292 |
+
|
| 1293 |
+
async def flush(self, force=False):
|
| 1294 |
+
if self.closed:
|
| 1295 |
+
raise ValueError("Flush on closed file")
|
| 1296 |
+
if force and self.forced:
|
| 1297 |
+
raise ValueError("Force flush cannot be called more than once")
|
| 1298 |
+
if force:
|
| 1299 |
+
self.forced = True
|
| 1300 |
+
|
| 1301 |
+
if self.mode not in {"wb", "ab"}:
|
| 1302 |
+
# no-op to flush on read-mode
|
| 1303 |
+
return
|
| 1304 |
+
|
| 1305 |
+
if not force and self.buffer.tell() < self.blocksize:
|
| 1306 |
+
# Defer write on small block
|
| 1307 |
+
return
|
| 1308 |
+
|
| 1309 |
+
if self.offset is None:
|
| 1310 |
+
# Initialize a multipart upload
|
| 1311 |
+
self.offset = 0
|
| 1312 |
+
try:
|
| 1313 |
+
await self._initiate_upload()
|
| 1314 |
+
except:
|
| 1315 |
+
self.closed = True
|
| 1316 |
+
raise
|
| 1317 |
+
|
| 1318 |
+
if await self._upload_chunk(final=force) is not False:
|
| 1319 |
+
self.offset += self.buffer.seek(0, 2)
|
| 1320 |
+
self.buffer = io.BytesIO()
|
| 1321 |
+
|
| 1322 |
+
async def __aenter__(self):
|
| 1323 |
+
return self
|
| 1324 |
+
|
| 1325 |
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
| 1326 |
+
await self.close()
|
| 1327 |
+
|
| 1328 |
+
async def _fetch_range(self, start, end):
|
| 1329 |
+
raise NotImplementedError
|
| 1330 |
+
|
| 1331 |
+
async def _initiate_upload(self):
|
| 1332 |
+
pass
|
| 1333 |
+
|
| 1334 |
+
async def _upload_chunk(self, final=False):
|
| 1335 |
+
raise NotImplementedError
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/caching.py
ADDED
|
@@ -0,0 +1,1158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import collections
|
| 5 |
+
import functools
|
| 6 |
+
import logging
|
| 7 |
+
import math
|
| 8 |
+
import os
|
| 9 |
+
import threading
|
| 10 |
+
from collections import OrderedDict
|
| 11 |
+
from collections.abc import Callable
|
| 12 |
+
from concurrent.futures import Future, ThreadPoolExecutor
|
| 13 |
+
from itertools import groupby
|
| 14 |
+
from operator import itemgetter
|
| 15 |
+
from typing import TYPE_CHECKING, Any, ClassVar, Generic, NamedTuple, TypeVar
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
import mmap
|
| 19 |
+
|
| 20 |
+
from typing_extensions import ParamSpec
|
| 21 |
+
|
| 22 |
+
P = ParamSpec("P")
|
| 23 |
+
else:
|
| 24 |
+
P = TypeVar("P")
|
| 25 |
+
|
| 26 |
+
T = TypeVar("T")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger("fsspec.caching")
|
| 30 |
+
|
| 31 |
+
Fetcher = Callable[[int, int], bytes] # Maps (start, end) to bytes
|
| 32 |
+
MultiFetcher = Callable[[list[int, int]], bytes] # Maps [(start, end)] to bytes
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class BaseCache:
|
| 36 |
+
"""Pass-though cache: doesn't keep anything, calls every time
|
| 37 |
+
|
| 38 |
+
Acts as base class for other cachers
|
| 39 |
+
|
| 40 |
+
Parameters
|
| 41 |
+
----------
|
| 42 |
+
blocksize: int
|
| 43 |
+
How far to read ahead in numbers of bytes
|
| 44 |
+
fetcher: func
|
| 45 |
+
Function of the form f(start, end) which gets bytes from remote as
|
| 46 |
+
specified
|
| 47 |
+
size: int
|
| 48 |
+
How big this file is
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
name: ClassVar[str] = "none"
|
| 52 |
+
|
| 53 |
+
def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None:
|
| 54 |
+
self.blocksize = blocksize
|
| 55 |
+
self.nblocks = 0
|
| 56 |
+
self.fetcher = fetcher
|
| 57 |
+
self.size = size
|
| 58 |
+
self.hit_count = 0
|
| 59 |
+
self.miss_count = 0
|
| 60 |
+
# the bytes that we actually requested
|
| 61 |
+
self.total_requested_bytes = 0
|
| 62 |
+
|
| 63 |
+
def _fetch(self, start: int | None, stop: int | None) -> bytes:
|
| 64 |
+
if start is None:
|
| 65 |
+
start = 0
|
| 66 |
+
if stop is None:
|
| 67 |
+
stop = self.size
|
| 68 |
+
if start >= self.size or start >= stop:
|
| 69 |
+
return b""
|
| 70 |
+
return self.fetcher(start, stop)
|
| 71 |
+
|
| 72 |
+
def _reset_stats(self) -> None:
|
| 73 |
+
"""Reset hit and miss counts for a more ganular report e.g. by file."""
|
| 74 |
+
self.hit_count = 0
|
| 75 |
+
self.miss_count = 0
|
| 76 |
+
self.total_requested_bytes = 0
|
| 77 |
+
|
| 78 |
+
def _log_stats(self) -> str:
|
| 79 |
+
"""Return a formatted string of the cache statistics."""
|
| 80 |
+
if self.hit_count == 0 and self.miss_count == 0:
|
| 81 |
+
# a cache that does nothing, this is for logs only
|
| 82 |
+
return ""
|
| 83 |
+
return f" , {self.name}: {self.hit_count} hits, {self.miss_count} misses, {self.total_requested_bytes} total requested bytes"
|
| 84 |
+
|
| 85 |
+
def __repr__(self) -> str:
|
| 86 |
+
# TODO: use rich for better formatting
|
| 87 |
+
return f"""
|
| 88 |
+
<{self.__class__.__name__}:
|
| 89 |
+
block size : {self.blocksize}
|
| 90 |
+
block count : {self.nblocks}
|
| 91 |
+
file size : {self.size}
|
| 92 |
+
cache hits : {self.hit_count}
|
| 93 |
+
cache misses: {self.miss_count}
|
| 94 |
+
total requested bytes: {self.total_requested_bytes}>
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class MMapCache(BaseCache):
|
| 99 |
+
"""memory-mapped sparse file cache
|
| 100 |
+
|
| 101 |
+
Opens temporary file, which is filled blocks-wise when data is requested.
|
| 102 |
+
Ensure there is enough disc space in the temporary location.
|
| 103 |
+
|
| 104 |
+
This cache method might only work on posix
|
| 105 |
+
|
| 106 |
+
Parameters
|
| 107 |
+
----------
|
| 108 |
+
blocksize: int
|
| 109 |
+
How far to read ahead in numbers of bytes
|
| 110 |
+
fetcher: Fetcher
|
| 111 |
+
Function of the form f(start, end) which gets bytes from remote as
|
| 112 |
+
specified
|
| 113 |
+
size: int
|
| 114 |
+
How big this file is
|
| 115 |
+
location: str
|
| 116 |
+
Where to create the temporary file. If None, a temporary file is
|
| 117 |
+
created using tempfile.TemporaryFile().
|
| 118 |
+
blocks: set[int]
|
| 119 |
+
Set of block numbers that have already been fetched. If None, an empty
|
| 120 |
+
set is created.
|
| 121 |
+
multi_fetcher: MultiFetcher
|
| 122 |
+
Function of the form f([(start, end)]) which gets bytes from remote
|
| 123 |
+
as specified. This function is used to fetch multiple blocks at once.
|
| 124 |
+
If not specified, the fetcher function is used instead.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
name = "mmap"
|
| 128 |
+
|
| 129 |
+
def __init__(
|
| 130 |
+
self,
|
| 131 |
+
blocksize: int,
|
| 132 |
+
fetcher: Fetcher,
|
| 133 |
+
size: int,
|
| 134 |
+
location: str | None = None,
|
| 135 |
+
blocks: set[int] | None = None,
|
| 136 |
+
multi_fetcher: MultiFetcher | None = None,
|
| 137 |
+
) -> None:
|
| 138 |
+
super().__init__(blocksize, fetcher, size)
|
| 139 |
+
self.blocks = set() if blocks is None else blocks
|
| 140 |
+
self.location = location
|
| 141 |
+
self.multi_fetcher = multi_fetcher
|
| 142 |
+
self.cache = self._makefile()
|
| 143 |
+
|
| 144 |
+
def _makefile(self) -> mmap.mmap | bytearray:
|
| 145 |
+
import mmap
|
| 146 |
+
import tempfile
|
| 147 |
+
|
| 148 |
+
if self.size == 0:
|
| 149 |
+
return bytearray()
|
| 150 |
+
|
| 151 |
+
# posix version
|
| 152 |
+
if self.location is None or not os.path.exists(self.location):
|
| 153 |
+
self.blocks.clear()
|
| 154 |
+
if self.location is None:
|
| 155 |
+
fd = tempfile.TemporaryFile()
|
| 156 |
+
else:
|
| 157 |
+
fd = open(self.location, "wb+")
|
| 158 |
+
fd.seek(self.size - 1)
|
| 159 |
+
fd.write(b"1")
|
| 160 |
+
fd.flush()
|
| 161 |
+
else:
|
| 162 |
+
fd = open(self.location, "r+b")
|
| 163 |
+
|
| 164 |
+
return mmap.mmap(fd.fileno(), self.size)
|
| 165 |
+
|
| 166 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 167 |
+
logger.debug(f"MMap cache fetching {start}-{end}")
|
| 168 |
+
if start is None:
|
| 169 |
+
start = 0
|
| 170 |
+
if end is None:
|
| 171 |
+
end = self.size
|
| 172 |
+
if start >= self.size or start >= end:
|
| 173 |
+
return b""
|
| 174 |
+
start_block = start // self.blocksize
|
| 175 |
+
end_block = end // self.blocksize
|
| 176 |
+
block_range = range(start_block, end_block + 1)
|
| 177 |
+
# Determine which blocks need to be fetched. This sequence is sorted by construction.
|
| 178 |
+
need = (i for i in block_range if i not in self.blocks)
|
| 179 |
+
# Count the number of blocks already cached
|
| 180 |
+
self.hit_count += sum(1 for i in block_range if i in self.blocks)
|
| 181 |
+
|
| 182 |
+
ranges = []
|
| 183 |
+
block_groups = []
|
| 184 |
+
|
| 185 |
+
# Consolidate needed blocks.
|
| 186 |
+
# Algorithm adapted from Python 2.x itertools documentation.
|
| 187 |
+
# We are grouping an enumerated sequence of blocks. By comparing when the difference
|
| 188 |
+
# between an ascending range (provided by enumerate) and the needed block numbers
|
| 189 |
+
# we can detect when the block number skips values. The key computes this difference.
|
| 190 |
+
# Whenever the difference changes, we know that we have previously cached block(s),
|
| 191 |
+
# and a new group is started. In other words, this algorithm neatly groups
|
| 192 |
+
# runs of consecutive block numbers so they can be fetched together.
|
| 193 |
+
for _, _blocks in groupby(enumerate(need), key=lambda x: x[0] - x[1]):
|
| 194 |
+
# Extract the blocks from the enumerated sequence
|
| 195 |
+
_blocks = tuple(map(itemgetter(1), _blocks))
|
| 196 |
+
# Compute start of first block
|
| 197 |
+
sstart = _blocks[0] * self.blocksize
|
| 198 |
+
# Compute the end of the last block. Last block may not be full size.
|
| 199 |
+
send = min(_blocks[-1] * self.blocksize + self.blocksize, self.size)
|
| 200 |
+
|
| 201 |
+
# Fetch bytes (could be multiple consecutive blocks)
|
| 202 |
+
self.total_requested_bytes += send - sstart
|
| 203 |
+
logger.debug(
|
| 204 |
+
f"MMap get blocks {_blocks[0]}-{_blocks[-1]} ({sstart}-{send})"
|
| 205 |
+
)
|
| 206 |
+
ranges.append((sstart, send))
|
| 207 |
+
block_groups.append(_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 |
+
self.blocks.update(block_groups[idx])
|
| 221 |
+
else:
|
| 222 |
+
for idx, (sstart, send) in enumerate(ranges):
|
| 223 |
+
logger.debug(f"MMap get block ({sstart}-{send}")
|
| 224 |
+
self.cache[sstart:send] = self.fetcher(sstart, send)
|
| 225 |
+
self.blocks.update(block_groups[idx])
|
| 226 |
+
|
| 227 |
+
return self.cache[start:end]
|
| 228 |
+
|
| 229 |
+
def close(self) -> None:
|
| 230 |
+
if hasattr(self.cache, "close"):
|
| 231 |
+
self.cache.close()
|
| 232 |
+
|
| 233 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 234 |
+
state = self.__dict__.copy()
|
| 235 |
+
# Remove the unpicklable entries.
|
| 236 |
+
del state["cache"]
|
| 237 |
+
return state
|
| 238 |
+
|
| 239 |
+
def __setstate__(self, state: dict[str, Any]) -> None:
|
| 240 |
+
# Restore instance attributes
|
| 241 |
+
self.__dict__.update(state)
|
| 242 |
+
self.cache = self._makefile()
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class ReadAheadCache(BaseCache):
|
| 246 |
+
"""Cache which reads only when we get beyond a block of data
|
| 247 |
+
|
| 248 |
+
This is a much simpler version of BytesCache, and does not attempt to
|
| 249 |
+
fill holes in the cache or keep fragments alive. It is best suited to
|
| 250 |
+
many small reads in a sequential order (e.g., reading lines from a file).
|
| 251 |
+
"""
|
| 252 |
+
|
| 253 |
+
name = "readahead"
|
| 254 |
+
|
| 255 |
+
def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None:
|
| 256 |
+
super().__init__(blocksize, fetcher, size)
|
| 257 |
+
self.cache = b""
|
| 258 |
+
self.start = 0
|
| 259 |
+
self.end = 0
|
| 260 |
+
|
| 261 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 262 |
+
if start is None:
|
| 263 |
+
start = 0
|
| 264 |
+
if end is None or end > self.size:
|
| 265 |
+
end = self.size
|
| 266 |
+
if start >= self.size or start >= end:
|
| 267 |
+
return b""
|
| 268 |
+
l = end - start
|
| 269 |
+
if start >= self.start and end <= self.end:
|
| 270 |
+
# cache hit
|
| 271 |
+
self.hit_count += 1
|
| 272 |
+
return self.cache[start - self.start : end - self.start]
|
| 273 |
+
elif self.start <= start < self.end:
|
| 274 |
+
# partial hit
|
| 275 |
+
self.miss_count += 1
|
| 276 |
+
part = self.cache[start - self.start :]
|
| 277 |
+
l -= len(part)
|
| 278 |
+
start = self.end
|
| 279 |
+
else:
|
| 280 |
+
# miss
|
| 281 |
+
self.miss_count += 1
|
| 282 |
+
part = b""
|
| 283 |
+
end = min(self.size, end + self.blocksize)
|
| 284 |
+
self.total_requested_bytes += end - start
|
| 285 |
+
self.cache = self.fetcher(start, end) # new block replaces old
|
| 286 |
+
self.start = start
|
| 287 |
+
self.end = self.start + len(self.cache)
|
| 288 |
+
return part + self.cache[:l]
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class AdaptiveReadaheadCache(BaseCache):
|
| 292 |
+
"""Cache with adaptive asynchronous prefetching.
|
| 293 |
+
|
| 294 |
+
Optimized for sequential and near-sequential reads by dynamically
|
| 295 |
+
adjusting the amount of data prefetched in the background. The cache
|
| 296 |
+
uses the generic prefetch engine when async loop support is available,
|
| 297 |
+
and falls back to ``ReadAheadCache`` when it is not.
|
| 298 |
+
|
| 299 |
+
Parameters
|
| 300 |
+
----------
|
| 301 |
+
blocksize: int
|
| 302 |
+
Nominal read size used by callers.
|
| 303 |
+
fetcher: Fetcher
|
| 304 |
+
Function of the form ``f(start, end)`` that returns bytes.
|
| 305 |
+
size: int
|
| 306 |
+
Total size of the file.
|
| 307 |
+
concurrency: int
|
| 308 |
+
Maximum number of concurrent background fetch tasks.
|
| 309 |
+
max_prefetch_size: int | None
|
| 310 |
+
Optional upper bound for adaptive prefetch size in bytes.
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
name = "adaptive"
|
| 314 |
+
|
| 315 |
+
def __init__(
|
| 316 |
+
self,
|
| 317 |
+
blocksize: int,
|
| 318 |
+
fetcher: Fetcher,
|
| 319 |
+
size: int,
|
| 320 |
+
concurrency: int = 4,
|
| 321 |
+
max_prefetch_size: int | None = None,
|
| 322 |
+
) -> None:
|
| 323 |
+
super().__init__(blocksize, fetcher, size)
|
| 324 |
+
self._fallback = ReadAheadCache(blocksize, fetcher, size)
|
| 325 |
+
self._prefetcher = None
|
| 326 |
+
|
| 327 |
+
async def _default_fetcher_async(
|
| 328 |
+
start_offset: int,
|
| 329 |
+
total_size: int,
|
| 330 |
+
split_factor: int = 1,
|
| 331 |
+
) -> bytes:
|
| 332 |
+
del split_factor
|
| 333 |
+
return await asyncio.to_thread(
|
| 334 |
+
self.fetcher, start_offset, start_offset + total_size
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
try:
|
| 338 |
+
from . import asyn as fsspec_asyn
|
| 339 |
+
except ImportError as e:
|
| 340 |
+
raise ImportError(
|
| 341 |
+
"AdaptiveReadaheadCache requires fsspec.asyn to be available"
|
| 342 |
+
) from e
|
| 343 |
+
|
| 344 |
+
try:
|
| 345 |
+
from .prefetcher import BackgroundPrefetcher
|
| 346 |
+
|
| 347 |
+
try:
|
| 348 |
+
fs_loop = fetcher.__self__.fs.loop
|
| 349 |
+
except AttributeError:
|
| 350 |
+
fs_loop = None
|
| 351 |
+
self._prefetcher = BackgroundPrefetcher(
|
| 352 |
+
fetcher=_default_fetcher_async,
|
| 353 |
+
size=size,
|
| 354 |
+
concurrency=concurrency,
|
| 355 |
+
max_prefetch_size=max_prefetch_size,
|
| 356 |
+
loop=(
|
| 357 |
+
fs_loop
|
| 358 |
+
if isinstance(fs_loop, asyncio.AbstractEventLoop)
|
| 359 |
+
else fsspec_asyn.get_loop()
|
| 360 |
+
),
|
| 361 |
+
)
|
| 362 |
+
logger.info(
|
| 363 |
+
"AdaptiveReadaheadCache enabled (blocksize=%d, size=%d, concurrency=%d, max_prefetch_size=%s)",
|
| 364 |
+
blocksize,
|
| 365 |
+
size,
|
| 366 |
+
concurrency,
|
| 367 |
+
max_prefetch_size,
|
| 368 |
+
)
|
| 369 |
+
except Exception as e:
|
| 370 |
+
logger.info(
|
| 371 |
+
"AdaptiveReadaheadCache fallback to ReadAheadCache: %s",
|
| 372 |
+
e,
|
| 373 |
+
exc_info=True,
|
| 374 |
+
)
|
| 375 |
+
self._prefetcher = None
|
| 376 |
+
|
| 377 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 378 |
+
if self._prefetcher is None:
|
| 379 |
+
out = self._fallback._fetch(start, end)
|
| 380 |
+
self.hit_count = self._fallback.hit_count
|
| 381 |
+
self.miss_count = self._fallback.miss_count
|
| 382 |
+
self.total_requested_bytes = self._fallback.total_requested_bytes
|
| 383 |
+
return out
|
| 384 |
+
|
| 385 |
+
out = self._prefetcher.fetch(start, end)
|
| 386 |
+
self.miss_count += 1
|
| 387 |
+
self.total_requested_bytes += len(out)
|
| 388 |
+
return out
|
| 389 |
+
|
| 390 |
+
def close(self) -> None:
|
| 391 |
+
if self._prefetcher is not None:
|
| 392 |
+
self._prefetcher.close()
|
| 393 |
+
self._prefetcher = None
|
| 394 |
+
|
| 395 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 396 |
+
# The prefetcher owns asyncio primitives that are not picklable.
|
| 397 |
+
self.close()
|
| 398 |
+
state = self.__dict__.copy()
|
| 399 |
+
state["_prefetcher"] = None
|
| 400 |
+
return state
|
| 401 |
+
|
| 402 |
+
def __setstate__(self, state: dict[str, Any]) -> None:
|
| 403 |
+
self.__dict__.update(state)
|
| 404 |
+
self._prefetcher = None
|
| 405 |
+
|
| 406 |
+
def __del__(self):
|
| 407 |
+
try:
|
| 408 |
+
self.close()
|
| 409 |
+
except Exception:
|
| 410 |
+
# Best-effort cleanup during GC.
|
| 411 |
+
pass
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class FirstChunkCache(BaseCache):
|
| 415 |
+
"""Caches the first block of a file only
|
| 416 |
+
|
| 417 |
+
This may be useful for file types where the metadata is stored in the header,
|
| 418 |
+
but is randomly accessed.
|
| 419 |
+
"""
|
| 420 |
+
|
| 421 |
+
name = "first"
|
| 422 |
+
|
| 423 |
+
def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None:
|
| 424 |
+
if blocksize > size:
|
| 425 |
+
# this will buffer the whole thing
|
| 426 |
+
blocksize = size
|
| 427 |
+
super().__init__(blocksize, fetcher, size)
|
| 428 |
+
self.cache: bytes | None = None
|
| 429 |
+
|
| 430 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 431 |
+
start = start or 0
|
| 432 |
+
if start > self.size:
|
| 433 |
+
logger.debug("FirstChunkCache: requested start > file size")
|
| 434 |
+
return b""
|
| 435 |
+
|
| 436 |
+
if end is None:
|
| 437 |
+
end = self.size
|
| 438 |
+
end = min(end, self.size)
|
| 439 |
+
|
| 440 |
+
if start < self.blocksize:
|
| 441 |
+
if self.cache is None:
|
| 442 |
+
self.miss_count += 1
|
| 443 |
+
if end > self.blocksize:
|
| 444 |
+
self.total_requested_bytes += end
|
| 445 |
+
data = self.fetcher(0, end)
|
| 446 |
+
self.cache = data[: self.blocksize]
|
| 447 |
+
return data[start:]
|
| 448 |
+
self.cache = self.fetcher(0, self.blocksize)
|
| 449 |
+
self.total_requested_bytes += self.blocksize
|
| 450 |
+
part = self.cache[start:end]
|
| 451 |
+
if end > self.blocksize:
|
| 452 |
+
self.total_requested_bytes += end - self.blocksize
|
| 453 |
+
part += self.fetcher(self.blocksize, end)
|
| 454 |
+
self.hit_count += 1
|
| 455 |
+
return part
|
| 456 |
+
else:
|
| 457 |
+
self.miss_count += 1
|
| 458 |
+
self.total_requested_bytes += end - start
|
| 459 |
+
return self.fetcher(start, end)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
class BlockCache(BaseCache):
|
| 463 |
+
"""
|
| 464 |
+
Cache holding memory as a set of blocks.
|
| 465 |
+
|
| 466 |
+
Requests are only ever made ``blocksize`` at a time, and are
|
| 467 |
+
stored in an LRU cache. The least recently accessed block is
|
| 468 |
+
discarded when more than ``maxblocks`` are stored.
|
| 469 |
+
|
| 470 |
+
Parameters
|
| 471 |
+
----------
|
| 472 |
+
blocksize : int
|
| 473 |
+
The number of bytes to store in each block.
|
| 474 |
+
Requests are only ever made for ``blocksize``, so this
|
| 475 |
+
should balance the overhead of making a request against
|
| 476 |
+
the granularity of the blocks.
|
| 477 |
+
fetcher : Callable
|
| 478 |
+
size : int
|
| 479 |
+
The total size of the file being cached.
|
| 480 |
+
maxblocks : int
|
| 481 |
+
The maximum number of blocks to cache for. The maximum memory
|
| 482 |
+
use for this cache is then ``blocksize * maxblocks``.
|
| 483 |
+
"""
|
| 484 |
+
|
| 485 |
+
name = "blockcache"
|
| 486 |
+
|
| 487 |
+
def __init__(
|
| 488 |
+
self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32
|
| 489 |
+
) -> None:
|
| 490 |
+
super().__init__(blocksize, fetcher, size)
|
| 491 |
+
self.nblocks = math.ceil(size / blocksize)
|
| 492 |
+
self.maxblocks = maxblocks
|
| 493 |
+
self._fetch_block_cached = functools.lru_cache(maxblocks)(self._fetch_block)
|
| 494 |
+
|
| 495 |
+
def cache_info(self):
|
| 496 |
+
"""
|
| 497 |
+
The statistics on the block cache.
|
| 498 |
+
|
| 499 |
+
Returns
|
| 500 |
+
-------
|
| 501 |
+
NamedTuple
|
| 502 |
+
Returned directly from the LRU Cache used internally.
|
| 503 |
+
"""
|
| 504 |
+
return self._fetch_block_cached.cache_info()
|
| 505 |
+
|
| 506 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 507 |
+
state = self.__dict__.copy()
|
| 508 |
+
del state["_fetch_block_cached"]
|
| 509 |
+
return state
|
| 510 |
+
|
| 511 |
+
def __setstate__(self, state: dict[str, Any]) -> None:
|
| 512 |
+
self.__dict__.update(state)
|
| 513 |
+
self._fetch_block_cached = functools.lru_cache(state["maxblocks"])(
|
| 514 |
+
self._fetch_block
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 518 |
+
if start is None:
|
| 519 |
+
start = 0
|
| 520 |
+
if end is None or end > self.size:
|
| 521 |
+
end = self.size
|
| 522 |
+
if start >= self.size or start >= end:
|
| 523 |
+
return b""
|
| 524 |
+
|
| 525 |
+
return self._read_cache(
|
| 526 |
+
start, end, start // self.blocksize, (end - 1) // self.blocksize
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
def _fetch_block(self, block_number: int) -> bytes:
|
| 530 |
+
"""
|
| 531 |
+
Fetch the block of data for `block_number`.
|
| 532 |
+
"""
|
| 533 |
+
if block_number > self.nblocks:
|
| 534 |
+
raise ValueError(
|
| 535 |
+
f"'block_number={block_number}' is greater than "
|
| 536 |
+
f"the number of blocks ({self.nblocks})"
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
start = block_number * self.blocksize
|
| 540 |
+
if start >= self.size:
|
| 541 |
+
return b""
|
| 542 |
+
end = min(start + self.blocksize, self.size)
|
| 543 |
+
self.total_requested_bytes += end - start
|
| 544 |
+
self.miss_count += 1
|
| 545 |
+
logger.info("BlockCache fetching block %d", block_number)
|
| 546 |
+
block_contents = super()._fetch(start, end)
|
| 547 |
+
return block_contents
|
| 548 |
+
|
| 549 |
+
def _read_cache(
|
| 550 |
+
self, start: int, end: int, start_block_number: int, end_block_number: int
|
| 551 |
+
) -> bytes:
|
| 552 |
+
"""
|
| 553 |
+
Read from our block cache.
|
| 554 |
+
|
| 555 |
+
Parameters
|
| 556 |
+
----------
|
| 557 |
+
start, end : int
|
| 558 |
+
The start and end byte positions.
|
| 559 |
+
start_block_number, end_block_number : int
|
| 560 |
+
The start and end block numbers.
|
| 561 |
+
"""
|
| 562 |
+
start_pos = start % self.blocksize
|
| 563 |
+
end_pos = end % self.blocksize
|
| 564 |
+
if end_pos == 0:
|
| 565 |
+
end_pos = self.blocksize
|
| 566 |
+
|
| 567 |
+
self.hit_count += 1
|
| 568 |
+
if start_block_number == end_block_number:
|
| 569 |
+
block: bytes = self._fetch_block_cached(start_block_number)
|
| 570 |
+
return block[start_pos:end_pos]
|
| 571 |
+
|
| 572 |
+
else:
|
| 573 |
+
# read from the initial
|
| 574 |
+
out = [self._fetch_block_cached(start_block_number)[start_pos:]]
|
| 575 |
+
|
| 576 |
+
# intermediate blocks
|
| 577 |
+
# Note: it'd be nice to combine these into one big request. However
|
| 578 |
+
# that doesn't play nicely with our LRU cache.
|
| 579 |
+
out.extend(
|
| 580 |
+
map(
|
| 581 |
+
self._fetch_block_cached,
|
| 582 |
+
range(start_block_number + 1, end_block_number),
|
| 583 |
+
)
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
# final block
|
| 587 |
+
out.append(self._fetch_block_cached(end_block_number)[:end_pos])
|
| 588 |
+
|
| 589 |
+
return b"".join(out)
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
class BytesCache(BaseCache):
|
| 593 |
+
"""Cache which holds data in a in-memory bytes object
|
| 594 |
+
|
| 595 |
+
Implements read-ahead by the block size, for semi-random reads progressing
|
| 596 |
+
through the file.
|
| 597 |
+
|
| 598 |
+
Parameters
|
| 599 |
+
----------
|
| 600 |
+
trim: bool
|
| 601 |
+
As we read more data, whether to discard the start of the buffer when
|
| 602 |
+
we are more than a blocksize ahead of it.
|
| 603 |
+
"""
|
| 604 |
+
|
| 605 |
+
name: ClassVar[str] = "bytes"
|
| 606 |
+
|
| 607 |
+
def __init__(
|
| 608 |
+
self, blocksize: int, fetcher: Fetcher, size: int, trim: bool = True
|
| 609 |
+
) -> None:
|
| 610 |
+
super().__init__(blocksize, fetcher, size)
|
| 611 |
+
self.cache = b""
|
| 612 |
+
self.start: int | None = None
|
| 613 |
+
self.end: int | None = None
|
| 614 |
+
self.trim = trim
|
| 615 |
+
|
| 616 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 617 |
+
# TODO: only set start/end after fetch, in case it fails?
|
| 618 |
+
# is this where retry logic might go?
|
| 619 |
+
if start is None:
|
| 620 |
+
start = 0
|
| 621 |
+
if end is None:
|
| 622 |
+
end = self.size
|
| 623 |
+
if start >= self.size or start >= end:
|
| 624 |
+
return b""
|
| 625 |
+
if (
|
| 626 |
+
self.start is not None
|
| 627 |
+
and start >= self.start
|
| 628 |
+
and self.end is not None
|
| 629 |
+
and end <= self.end
|
| 630 |
+
):
|
| 631 |
+
# cache hit: we have all the required data
|
| 632 |
+
offset = start - self.start
|
| 633 |
+
self.hit_count += 1
|
| 634 |
+
return self.cache[offset : offset + end - start]
|
| 635 |
+
|
| 636 |
+
if self.blocksize:
|
| 637 |
+
bend = min(self.size, end + self.blocksize)
|
| 638 |
+
else:
|
| 639 |
+
bend = end
|
| 640 |
+
|
| 641 |
+
if bend == start or start > self.size:
|
| 642 |
+
return b""
|
| 643 |
+
|
| 644 |
+
if (self.start is None or start < self.start) and (
|
| 645 |
+
self.end is None or end > self.end
|
| 646 |
+
):
|
| 647 |
+
# First read, or extending both before and after
|
| 648 |
+
self.total_requested_bytes += bend - start
|
| 649 |
+
self.miss_count += 1
|
| 650 |
+
self.cache = self.fetcher(start, bend)
|
| 651 |
+
self.start = start
|
| 652 |
+
else:
|
| 653 |
+
assert self.start is not None
|
| 654 |
+
assert self.end is not None
|
| 655 |
+
self.miss_count += 1
|
| 656 |
+
|
| 657 |
+
if start < self.start:
|
| 658 |
+
if self.end is None or self.end - end > self.blocksize:
|
| 659 |
+
self.total_requested_bytes += bend - start
|
| 660 |
+
self.cache = self.fetcher(start, bend)
|
| 661 |
+
self.start = start
|
| 662 |
+
else:
|
| 663 |
+
self.total_requested_bytes += self.start - start
|
| 664 |
+
new = self.fetcher(start, self.start)
|
| 665 |
+
self.start = start
|
| 666 |
+
self.cache = new + self.cache
|
| 667 |
+
elif self.end is not None and bend > self.end:
|
| 668 |
+
if self.end > self.size:
|
| 669 |
+
pass
|
| 670 |
+
elif end - self.end > self.blocksize:
|
| 671 |
+
self.total_requested_bytes += bend - start
|
| 672 |
+
self.cache = self.fetcher(start, bend)
|
| 673 |
+
self.start = start
|
| 674 |
+
else:
|
| 675 |
+
self.total_requested_bytes += bend - self.end
|
| 676 |
+
new = self.fetcher(self.end, bend)
|
| 677 |
+
self.cache = self.cache + new
|
| 678 |
+
|
| 679 |
+
self.end = self.start + len(self.cache)
|
| 680 |
+
offset = start - self.start
|
| 681 |
+
out = self.cache[offset : offset + end - start]
|
| 682 |
+
if self.trim:
|
| 683 |
+
num = (self.end - self.start) // (self.blocksize + 1)
|
| 684 |
+
if num > 1:
|
| 685 |
+
self.start += self.blocksize * num
|
| 686 |
+
self.cache = self.cache[self.blocksize * num :]
|
| 687 |
+
return out
|
| 688 |
+
|
| 689 |
+
def __len__(self) -> int:
|
| 690 |
+
return len(self.cache)
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
class AllBytes(BaseCache):
|
| 694 |
+
"""Cache entire contents of the file"""
|
| 695 |
+
|
| 696 |
+
name: ClassVar[str] = "all"
|
| 697 |
+
|
| 698 |
+
def __init__(
|
| 699 |
+
self,
|
| 700 |
+
blocksize: int | None = None,
|
| 701 |
+
fetcher: Fetcher | None = None,
|
| 702 |
+
size: int | None = None,
|
| 703 |
+
data: bytes | None = None,
|
| 704 |
+
) -> None:
|
| 705 |
+
super().__init__(blocksize, fetcher, size) # type: ignore[arg-type]
|
| 706 |
+
if data is None:
|
| 707 |
+
self.miss_count += 1
|
| 708 |
+
self.total_requested_bytes += self.size
|
| 709 |
+
data = self.fetcher(0, self.size)
|
| 710 |
+
self.data = data
|
| 711 |
+
|
| 712 |
+
def _fetch(self, start: int | None, stop: int | None) -> bytes:
|
| 713 |
+
self.hit_count += 1
|
| 714 |
+
return self.data[start:stop]
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
class KnownPartsOfAFile(BaseCache):
|
| 718 |
+
"""
|
| 719 |
+
Cache holding known file parts.
|
| 720 |
+
|
| 721 |
+
Parameters
|
| 722 |
+
----------
|
| 723 |
+
blocksize: int
|
| 724 |
+
How far to read ahead in numbers of bytes
|
| 725 |
+
fetcher: func
|
| 726 |
+
Function of the form f(start, end) which gets bytes from remote as
|
| 727 |
+
specified
|
| 728 |
+
size: int
|
| 729 |
+
How big this file is
|
| 730 |
+
data: dict
|
| 731 |
+
A dictionary mapping explicit `(start, stop)` file-offset tuples
|
| 732 |
+
with known bytes.
|
| 733 |
+
strict: bool, default True
|
| 734 |
+
Whether to fetch reads that go beyond a known byte-range boundary.
|
| 735 |
+
If `False`, any read that ends outside a known part will be zero
|
| 736 |
+
padded. Note that zero padding will not be used for reads that
|
| 737 |
+
begin outside a known byte-range.
|
| 738 |
+
"""
|
| 739 |
+
|
| 740 |
+
name: ClassVar[str] = "parts"
|
| 741 |
+
|
| 742 |
+
def __init__(
|
| 743 |
+
self,
|
| 744 |
+
blocksize: int,
|
| 745 |
+
fetcher: Fetcher,
|
| 746 |
+
size: int,
|
| 747 |
+
data: dict[tuple[int, int], bytes] | None = None,
|
| 748 |
+
strict: bool = False,
|
| 749 |
+
**_: Any,
|
| 750 |
+
):
|
| 751 |
+
super().__init__(blocksize, fetcher, size)
|
| 752 |
+
self.strict = strict
|
| 753 |
+
|
| 754 |
+
# simple consolidation of contiguous blocks
|
| 755 |
+
if data:
|
| 756 |
+
old_offsets = sorted(data.keys())
|
| 757 |
+
offsets = [old_offsets[0]]
|
| 758 |
+
blocks = [data.pop(old_offsets[0])]
|
| 759 |
+
for start, stop in old_offsets[1:]:
|
| 760 |
+
start0, stop0 = offsets[-1]
|
| 761 |
+
if start == stop0:
|
| 762 |
+
offsets[-1] = (start0, stop)
|
| 763 |
+
blocks[-1] += data.pop((start, stop))
|
| 764 |
+
else:
|
| 765 |
+
offsets.append((start, stop))
|
| 766 |
+
blocks.append(data.pop((start, stop)))
|
| 767 |
+
|
| 768 |
+
self.data = dict(zip(offsets, blocks))
|
| 769 |
+
else:
|
| 770 |
+
self.data = {}
|
| 771 |
+
|
| 772 |
+
@property
|
| 773 |
+
def size(self):
|
| 774 |
+
return sum(_[1] - _[0] for _ in self.data)
|
| 775 |
+
|
| 776 |
+
@size.setter
|
| 777 |
+
def size(self, value):
|
| 778 |
+
pass
|
| 779 |
+
|
| 780 |
+
@property
|
| 781 |
+
def nblocks(self):
|
| 782 |
+
return len(self.data)
|
| 783 |
+
|
| 784 |
+
@nblocks.setter
|
| 785 |
+
def nblocks(self, value):
|
| 786 |
+
pass
|
| 787 |
+
|
| 788 |
+
def _fetch(self, start: int | None, stop: int | None) -> bytes:
|
| 789 |
+
logger.debug("Known parts request %s %s", start, stop)
|
| 790 |
+
if start is None:
|
| 791 |
+
start = 0
|
| 792 |
+
if stop is None:
|
| 793 |
+
stop = self.size
|
| 794 |
+
self.total_requested_bytes += stop - start
|
| 795 |
+
out = b""
|
| 796 |
+
started = False
|
| 797 |
+
loc_old = 0
|
| 798 |
+
for loc0, loc1 in sorted(self.data):
|
| 799 |
+
if (loc0 <= start < loc1) and (loc0 <= stop <= loc1):
|
| 800 |
+
# entirely within the block
|
| 801 |
+
off = start - loc0
|
| 802 |
+
self.hit_count += 1
|
| 803 |
+
return self.data[(loc0, loc1)][off : off + stop - start]
|
| 804 |
+
if stop <= loc0:
|
| 805 |
+
break
|
| 806 |
+
if started and loc0 > loc_old:
|
| 807 |
+
# a gap where we need data
|
| 808 |
+
self.miss_count += 1
|
| 809 |
+
if self.strict:
|
| 810 |
+
raise ValueError
|
| 811 |
+
out += b"\x00" * (loc0 - loc_old)
|
| 812 |
+
if loc0 <= start < loc1:
|
| 813 |
+
# found the start
|
| 814 |
+
self.hit_count += 1
|
| 815 |
+
off = start - loc0
|
| 816 |
+
out = self.data[(loc0, loc1)][off : off + stop - start]
|
| 817 |
+
started = True
|
| 818 |
+
elif start < loc0 and stop > loc1:
|
| 819 |
+
# the whole block
|
| 820 |
+
self.hit_count += 1
|
| 821 |
+
out += self.data[(loc0, loc1)]
|
| 822 |
+
elif started and loc0 <= stop <= loc1:
|
| 823 |
+
# end block. The start of the request must have been found in
|
| 824 |
+
# an earlier part, else these bytes come from the wrong offsets
|
| 825 |
+
self.hit_count += 1
|
| 826 |
+
out = out + self.data[(loc0, loc1)][: stop - loc0]
|
| 827 |
+
return out
|
| 828 |
+
loc_old = loc1
|
| 829 |
+
self.miss_count += 1
|
| 830 |
+
if started and not self.strict:
|
| 831 |
+
out = out + b"\x00" * (stop - loc_old)
|
| 832 |
+
return out
|
| 833 |
+
raise ValueError
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
class UpdatableLRU(Generic[P, T]):
|
| 837 |
+
"""
|
| 838 |
+
Custom implementation of LRU cache that allows updating keys
|
| 839 |
+
|
| 840 |
+
Used by BackgroundBlockCache
|
| 841 |
+
"""
|
| 842 |
+
|
| 843 |
+
class CacheInfo(NamedTuple):
|
| 844 |
+
hits: int
|
| 845 |
+
misses: int
|
| 846 |
+
maxsize: int
|
| 847 |
+
currsize: int
|
| 848 |
+
|
| 849 |
+
def __init__(self, func: Callable[P, T], max_size: int = 128) -> None:
|
| 850 |
+
self._cache: OrderedDict[Any, T] = collections.OrderedDict()
|
| 851 |
+
self._func = func
|
| 852 |
+
self._max_size = max_size
|
| 853 |
+
self._hits = 0
|
| 854 |
+
self._misses = 0
|
| 855 |
+
self._lock = threading.Lock()
|
| 856 |
+
|
| 857 |
+
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
|
| 858 |
+
if kwargs:
|
| 859 |
+
raise TypeError(f"Got unexpected keyword argument {kwargs.keys()}")
|
| 860 |
+
with self._lock:
|
| 861 |
+
if args in self._cache:
|
| 862 |
+
self._cache.move_to_end(args)
|
| 863 |
+
self._hits += 1
|
| 864 |
+
return self._cache[args]
|
| 865 |
+
|
| 866 |
+
result = self._func(*args, **kwargs)
|
| 867 |
+
|
| 868 |
+
with self._lock:
|
| 869 |
+
self._cache[args] = result
|
| 870 |
+
self._misses += 1
|
| 871 |
+
if len(self._cache) > self._max_size:
|
| 872 |
+
self._cache.popitem(last=False)
|
| 873 |
+
|
| 874 |
+
return result
|
| 875 |
+
|
| 876 |
+
def is_key_cached(self, *args: Any) -> bool:
|
| 877 |
+
with self._lock:
|
| 878 |
+
return args in self._cache
|
| 879 |
+
|
| 880 |
+
def add_key(self, result: T, *args: Any) -> None:
|
| 881 |
+
with self._lock:
|
| 882 |
+
self._cache[args] = result
|
| 883 |
+
if len(self._cache) > self._max_size:
|
| 884 |
+
self._cache.popitem(last=False)
|
| 885 |
+
|
| 886 |
+
def cache_info(self) -> UpdatableLRU.CacheInfo:
|
| 887 |
+
with self._lock:
|
| 888 |
+
return self.CacheInfo(
|
| 889 |
+
maxsize=self._max_size,
|
| 890 |
+
currsize=len(self._cache),
|
| 891 |
+
hits=self._hits,
|
| 892 |
+
misses=self._misses,
|
| 893 |
+
)
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
class BackgroundBlockCache(BaseCache):
|
| 897 |
+
"""
|
| 898 |
+
Cache holding memory as a set of blocks with pre-loading of
|
| 899 |
+
the next block in the background.
|
| 900 |
+
|
| 901 |
+
Requests are only ever made ``blocksize`` at a time, and are
|
| 902 |
+
stored in an LRU cache. The least recently accessed block is
|
| 903 |
+
discarded when more than ``maxblocks`` are stored. If the
|
| 904 |
+
next block is not in cache, it is loaded in a separate thread
|
| 905 |
+
in non-blocking way.
|
| 906 |
+
|
| 907 |
+
Parameters
|
| 908 |
+
----------
|
| 909 |
+
blocksize : int
|
| 910 |
+
The number of bytes to store in each block.
|
| 911 |
+
Requests are only ever made for ``blocksize``, so this
|
| 912 |
+
should balance the overhead of making a request against
|
| 913 |
+
the granularity of the blocks.
|
| 914 |
+
fetcher : Callable
|
| 915 |
+
size : int
|
| 916 |
+
The total size of the file being cached.
|
| 917 |
+
maxblocks : int
|
| 918 |
+
The maximum number of blocks to cache for. The maximum memory
|
| 919 |
+
use for this cache is then ``blocksize * maxblocks``.
|
| 920 |
+
"""
|
| 921 |
+
|
| 922 |
+
name: ClassVar[str] = "background"
|
| 923 |
+
|
| 924 |
+
def __init__(
|
| 925 |
+
self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32
|
| 926 |
+
) -> None:
|
| 927 |
+
super().__init__(blocksize, fetcher, size)
|
| 928 |
+
self.nblocks = math.ceil(size / blocksize)
|
| 929 |
+
self.maxblocks = maxblocks
|
| 930 |
+
self._fetch_block_cached = UpdatableLRU(self._fetch_block, maxblocks)
|
| 931 |
+
|
| 932 |
+
self._thread_executor = ThreadPoolExecutor(max_workers=1)
|
| 933 |
+
self._fetch_future_block_number: int | None = None
|
| 934 |
+
self._fetch_future: Future[bytes] | None = None
|
| 935 |
+
self._fetch_future_lock = threading.Lock()
|
| 936 |
+
self._closed = False
|
| 937 |
+
|
| 938 |
+
def cache_info(self) -> UpdatableLRU.CacheInfo:
|
| 939 |
+
"""
|
| 940 |
+
The statistics on the block cache.
|
| 941 |
+
|
| 942 |
+
Returns
|
| 943 |
+
-------
|
| 944 |
+
NamedTuple
|
| 945 |
+
Returned directly from the LRU Cache used internally.
|
| 946 |
+
"""
|
| 947 |
+
return self._fetch_block_cached.cache_info()
|
| 948 |
+
|
| 949 |
+
def close(self) -> None:
|
| 950 |
+
"""Cancel pending work and shut down the background worker."""
|
| 951 |
+
with self._fetch_future_lock:
|
| 952 |
+
if self._closed:
|
| 953 |
+
return
|
| 954 |
+
self._closed = True
|
| 955 |
+
future = self._fetch_future
|
| 956 |
+
self._fetch_future = None
|
| 957 |
+
self._fetch_future_block_number = None
|
| 958 |
+
|
| 959 |
+
if future is not None:
|
| 960 |
+
future.cancel()
|
| 961 |
+
self._thread_executor.shutdown(wait=True, cancel_futures=True)
|
| 962 |
+
|
| 963 |
+
# UpdatableLRU stores a bound method and otherwise forms a reference cycle.
|
| 964 |
+
del self._fetch_block_cached
|
| 965 |
+
|
| 966 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 967 |
+
state = self.__dict__.copy()
|
| 968 |
+
del state["_fetch_block_cached"]
|
| 969 |
+
del state["_thread_executor"]
|
| 970 |
+
del state["_fetch_future_block_number"]
|
| 971 |
+
del state["_fetch_future"]
|
| 972 |
+
del state["_fetch_future_lock"]
|
| 973 |
+
return state
|
| 974 |
+
|
| 975 |
+
def __setstate__(self, state) -> None:
|
| 976 |
+
self.__dict__.update(state)
|
| 977 |
+
self._fetch_block_cached = UpdatableLRU(self._fetch_block, state["maxblocks"])
|
| 978 |
+
self._thread_executor = ThreadPoolExecutor(max_workers=1)
|
| 979 |
+
self._fetch_future_block_number = None
|
| 980 |
+
self._fetch_future = None
|
| 981 |
+
self._fetch_future_lock = threading.Lock()
|
| 982 |
+
self._closed = False
|
| 983 |
+
|
| 984 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 985 |
+
if start is None:
|
| 986 |
+
start = 0
|
| 987 |
+
if end is None or end > self.size:
|
| 988 |
+
end = self.size
|
| 989 |
+
if start >= self.size or start >= end:
|
| 990 |
+
return b""
|
| 991 |
+
|
| 992 |
+
# byte position -> block numbers; ``end`` is exclusive
|
| 993 |
+
start_block_number = start // self.blocksize
|
| 994 |
+
end_block_number = (end - 1) // self.blocksize
|
| 995 |
+
|
| 996 |
+
fetch_future_block_number = None
|
| 997 |
+
fetch_future = None
|
| 998 |
+
with self._fetch_future_lock:
|
| 999 |
+
# Background thread is running. Check we we can or must join it.
|
| 1000 |
+
if self._fetch_future is not None:
|
| 1001 |
+
assert self._fetch_future_block_number is not None
|
| 1002 |
+
if self._fetch_future.done():
|
| 1003 |
+
logger.info("BlockCache joined background fetch without waiting.")
|
| 1004 |
+
self._fetch_block_cached.add_key(
|
| 1005 |
+
self._fetch_future.result(), self._fetch_future_block_number
|
| 1006 |
+
)
|
| 1007 |
+
# Cleanup the fetch variables. Done with fetching the block.
|
| 1008 |
+
self._fetch_future_block_number = None
|
| 1009 |
+
self._fetch_future = None
|
| 1010 |
+
else:
|
| 1011 |
+
# Must join if we need the block for the current fetch
|
| 1012 |
+
must_join = bool(
|
| 1013 |
+
start_block_number
|
| 1014 |
+
<= self._fetch_future_block_number
|
| 1015 |
+
<= end_block_number
|
| 1016 |
+
)
|
| 1017 |
+
if must_join:
|
| 1018 |
+
# Copy to the local variables to release lock
|
| 1019 |
+
# before waiting for result
|
| 1020 |
+
fetch_future_block_number = self._fetch_future_block_number
|
| 1021 |
+
fetch_future = self._fetch_future
|
| 1022 |
+
|
| 1023 |
+
# Cleanup the fetch variables. Have a local copy.
|
| 1024 |
+
self._fetch_future_block_number = None
|
| 1025 |
+
self._fetch_future = None
|
| 1026 |
+
|
| 1027 |
+
# Need to wait for the future for the current read
|
| 1028 |
+
if fetch_future is not None:
|
| 1029 |
+
logger.info("BlockCache waiting for background fetch.")
|
| 1030 |
+
# Wait until result and put it in cache
|
| 1031 |
+
self._fetch_block_cached.add_key(
|
| 1032 |
+
fetch_future.result(), fetch_future_block_number
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
# fetch next block in the background if nothing is running in the background,
|
| 1036 |
+
# the block is within file and it is not already cached
|
| 1037 |
+
end_block_plus_1 = end_block_number + 1
|
| 1038 |
+
with self._fetch_future_lock:
|
| 1039 |
+
if (
|
| 1040 |
+
self._fetch_future is None
|
| 1041 |
+
and end_block_plus_1 <= self.nblocks
|
| 1042 |
+
and not self._fetch_block_cached.is_key_cached(end_block_plus_1)
|
| 1043 |
+
):
|
| 1044 |
+
self._fetch_future_block_number = end_block_plus_1
|
| 1045 |
+
self._fetch_future = self._thread_executor.submit(
|
| 1046 |
+
self._fetch_block, end_block_plus_1, "async"
|
| 1047 |
+
)
|
| 1048 |
+
|
| 1049 |
+
return self._read_cache(
|
| 1050 |
+
start,
|
| 1051 |
+
end,
|
| 1052 |
+
start_block_number=start_block_number,
|
| 1053 |
+
end_block_number=end_block_number,
|
| 1054 |
+
)
|
| 1055 |
+
|
| 1056 |
+
def _fetch_block(self, block_number: int, log_info: str = "sync") -> bytes:
|
| 1057 |
+
"""
|
| 1058 |
+
Fetch the block of data for `block_number`.
|
| 1059 |
+
"""
|
| 1060 |
+
if block_number > self.nblocks:
|
| 1061 |
+
raise ValueError(
|
| 1062 |
+
f"'block_number={block_number}' is greater than "
|
| 1063 |
+
f"the number of blocks ({self.nblocks})"
|
| 1064 |
+
)
|
| 1065 |
+
|
| 1066 |
+
start = block_number * self.blocksize
|
| 1067 |
+
if start >= self.size:
|
| 1068 |
+
return b""
|
| 1069 |
+
end = min(start + self.blocksize, self.size)
|
| 1070 |
+
logger.info("BlockCache fetching block (%s) %d", log_info, block_number)
|
| 1071 |
+
self.total_requested_bytes += end - start
|
| 1072 |
+
self.miss_count += 1
|
| 1073 |
+
block_contents = super()._fetch(start, end)
|
| 1074 |
+
return block_contents
|
| 1075 |
+
|
| 1076 |
+
def _read_cache(
|
| 1077 |
+
self, start: int, end: int, start_block_number: int, end_block_number: int
|
| 1078 |
+
) -> bytes:
|
| 1079 |
+
"""
|
| 1080 |
+
Read from our block cache.
|
| 1081 |
+
|
| 1082 |
+
Parameters
|
| 1083 |
+
----------
|
| 1084 |
+
start, end : int
|
| 1085 |
+
The start and end byte positions.
|
| 1086 |
+
start_block_number, end_block_number : int
|
| 1087 |
+
The start and end block numbers.
|
| 1088 |
+
"""
|
| 1089 |
+
start_pos = start % self.blocksize
|
| 1090 |
+
end_pos = end % self.blocksize
|
| 1091 |
+
if end_pos == 0:
|
| 1092 |
+
end_pos = self.blocksize
|
| 1093 |
+
|
| 1094 |
+
# kind of pointless to count this as a hit, but it is
|
| 1095 |
+
self.hit_count += 1
|
| 1096 |
+
|
| 1097 |
+
if start_block_number == end_block_number:
|
| 1098 |
+
block = self._fetch_block_cached(start_block_number)
|
| 1099 |
+
return block[start_pos:end_pos]
|
| 1100 |
+
|
| 1101 |
+
else:
|
| 1102 |
+
# read from the initial
|
| 1103 |
+
out = [self._fetch_block_cached(start_block_number)[start_pos:]]
|
| 1104 |
+
|
| 1105 |
+
# intermediate blocks
|
| 1106 |
+
# Note: it'd be nice to combine these into one big request. However
|
| 1107 |
+
# that doesn't play nicely with our LRU cache.
|
| 1108 |
+
out.extend(
|
| 1109 |
+
map(
|
| 1110 |
+
self._fetch_block_cached,
|
| 1111 |
+
range(start_block_number + 1, end_block_number),
|
| 1112 |
+
)
|
| 1113 |
+
)
|
| 1114 |
+
|
| 1115 |
+
# final block
|
| 1116 |
+
out.append(self._fetch_block_cached(end_block_number)[:end_pos])
|
| 1117 |
+
|
| 1118 |
+
return b"".join(out)
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
caches: dict[str | None, type[BaseCache]] = {
|
| 1122 |
+
# one custom case
|
| 1123 |
+
None: BaseCache,
|
| 1124 |
+
}
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
def register_cache(cls: type[BaseCache], clobber: bool = False) -> None:
|
| 1128 |
+
"""'Register' cache implementation.
|
| 1129 |
+
|
| 1130 |
+
Parameters
|
| 1131 |
+
----------
|
| 1132 |
+
clobber: bool, optional
|
| 1133 |
+
If set to True (default is False) - allow to overwrite existing
|
| 1134 |
+
entry.
|
| 1135 |
+
|
| 1136 |
+
Raises
|
| 1137 |
+
------
|
| 1138 |
+
ValueError
|
| 1139 |
+
"""
|
| 1140 |
+
name = cls.name
|
| 1141 |
+
if not clobber and name in caches:
|
| 1142 |
+
raise ValueError(f"Cache with name {name!r} is already known: {caches[name]}")
|
| 1143 |
+
caches[name] = cls
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
for c in (
|
| 1147 |
+
BaseCache,
|
| 1148 |
+
MMapCache,
|
| 1149 |
+
BytesCache,
|
| 1150 |
+
ReadAheadCache,
|
| 1151 |
+
AdaptiveReadaheadCache,
|
| 1152 |
+
BlockCache,
|
| 1153 |
+
FirstChunkCache,
|
| 1154 |
+
AllBytes,
|
| 1155 |
+
KnownPartsOfAFile,
|
| 1156 |
+
BackgroundBlockCache,
|
| 1157 |
+
):
|
| 1158 |
+
register_cache(c)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/callbacks.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/compression.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
|
| 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", "zstd"])
|
| 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", "zstd"])
|
| 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)
|
tasks/tasksmith-3bb3c78392c6/tests/source/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), encoding="utf-8")
|
| 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), encoding="utf-8") 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)
|
tasks/tasksmith-3bb3c78392c6/tests/source/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
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/core.py
ADDED
|
@@ -0,0 +1,765 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
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 |
+
f"{self.path} not found. "
|
| 110 |
+
"The URL contains glob characters: you maybe needed\n"
|
| 111 |
+
"to pass expand=True in fsspec.open() or the storage_options of \n"
|
| 112 |
+
"your library. You can also set the config value 'open_expand'\n"
|
| 113 |
+
"before import, or fsspec.core.DEFAULT_EXPAND at runtime, to True."
|
| 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" in self.mode:
|
| 196 |
+
# open_many() returns files without populating the OpenFile objects.
|
| 197 |
+
for f in self.files:
|
| 198 |
+
f.close()
|
| 199 |
+
else:
|
| 200 |
+
while True:
|
| 201 |
+
if hasattr(fs, "open_many"):
|
| 202 |
+
# check for concurrent cache upload
|
| 203 |
+
fs.commit_many(self.files)
|
| 204 |
+
return
|
| 205 |
+
if hasattr(fs, "fs") and fs.fs is not None:
|
| 206 |
+
fs = fs.fs
|
| 207 |
+
else:
|
| 208 |
+
break
|
| 209 |
+
|
| 210 |
+
def __getitem__(self, item):
|
| 211 |
+
out = super().__getitem__(item)
|
| 212 |
+
if isinstance(item, slice):
|
| 213 |
+
return OpenFiles(out, mode=self.mode, fs=self.fs)
|
| 214 |
+
return out
|
| 215 |
+
|
| 216 |
+
def __repr__(self):
|
| 217 |
+
return f"<List of {len(self)} OpenFile instances>"
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def open_files(
|
| 221 |
+
urlpath,
|
| 222 |
+
mode="rb",
|
| 223 |
+
compression=None,
|
| 224 |
+
encoding="utf8",
|
| 225 |
+
errors=None,
|
| 226 |
+
name_function=None,
|
| 227 |
+
num=1,
|
| 228 |
+
protocol=None,
|
| 229 |
+
newline=None,
|
| 230 |
+
auto_mkdir=True,
|
| 231 |
+
expand=True,
|
| 232 |
+
**kwargs,
|
| 233 |
+
):
|
| 234 |
+
"""Given a path or paths, return a list of ``OpenFile`` objects.
|
| 235 |
+
|
| 236 |
+
For writing, a str path must contain the "*" character, which will be filled
|
| 237 |
+
in by increasing numbers, e.g., "part*" -> "part1", "part2" if num=2.
|
| 238 |
+
|
| 239 |
+
For either reading or writing, can instead provide explicit list of paths.
|
| 240 |
+
|
| 241 |
+
Parameters
|
| 242 |
+
----------
|
| 243 |
+
urlpath: string or list
|
| 244 |
+
Absolute or relative filepath(s). Prefix with a protocol like ``s3://``
|
| 245 |
+
to read from alternative filesystems. To read from multiple files you
|
| 246 |
+
can pass a globstring or a list of paths, with the caveat that they
|
| 247 |
+
must all have the same protocol.
|
| 248 |
+
mode: 'rb', 'wt', etc.
|
| 249 |
+
compression: string or None
|
| 250 |
+
If given, open file using compression codec. Can either be a compression
|
| 251 |
+
name (a key in ``fsspec.compression.compr``) or "infer" to guess the
|
| 252 |
+
compression from the filename suffix.
|
| 253 |
+
encoding: str
|
| 254 |
+
For text mode only
|
| 255 |
+
errors: None or str
|
| 256 |
+
Passed to TextIOWrapper in text mode
|
| 257 |
+
name_function: function or None
|
| 258 |
+
if opening a set of files for writing, those files do not yet exist,
|
| 259 |
+
so we need to generate their names by formatting the urlpath for
|
| 260 |
+
each sequence number
|
| 261 |
+
num: int [1]
|
| 262 |
+
if writing mode, number of files we expect to create (passed to
|
| 263 |
+
name+function)
|
| 264 |
+
protocol: str or None
|
| 265 |
+
If given, overrides the protocol found in the URL.
|
| 266 |
+
newline: bytes or None
|
| 267 |
+
Used for line terminator in text mode. If None, uses system default;
|
| 268 |
+
if blank, uses no translation.
|
| 269 |
+
auto_mkdir: bool (True)
|
| 270 |
+
If in write mode, this will ensure the target directory exists before
|
| 271 |
+
writing, by calling ``fs.mkdirs(exist_ok=True)``.
|
| 272 |
+
expand: bool
|
| 273 |
+
**kwargs: dict
|
| 274 |
+
Extra options that make sense to a particular storage connection, e.g.
|
| 275 |
+
host, port, username, password, etc.
|
| 276 |
+
|
| 277 |
+
Examples
|
| 278 |
+
--------
|
| 279 |
+
>>> files = open_files('2015-*-*.csv') # doctest: +SKIP
|
| 280 |
+
>>> files = open_files(
|
| 281 |
+
... 's3://bucket/2015-*-*.csv.gz', compression='gzip'
|
| 282 |
+
... ) # doctest: +SKIP
|
| 283 |
+
|
| 284 |
+
Returns
|
| 285 |
+
-------
|
| 286 |
+
An ``OpenFiles`` instance, which is a list of ``OpenFile`` objects that can
|
| 287 |
+
be used as a single context
|
| 288 |
+
|
| 289 |
+
Notes
|
| 290 |
+
-----
|
| 291 |
+
For a full list of the available protocols and the implementations that
|
| 292 |
+
they map across to see the latest online documentation:
|
| 293 |
+
|
| 294 |
+
- For implementations built into ``fsspec`` see
|
| 295 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
|
| 296 |
+
- For implementations in separate packages see
|
| 297 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
|
| 298 |
+
"""
|
| 299 |
+
fs, fs_token, paths = get_fs_token_paths(
|
| 300 |
+
urlpath,
|
| 301 |
+
mode,
|
| 302 |
+
num=num,
|
| 303 |
+
name_function=name_function,
|
| 304 |
+
storage_options=kwargs,
|
| 305 |
+
protocol=protocol,
|
| 306 |
+
expand=expand,
|
| 307 |
+
)
|
| 308 |
+
if fs.protocol == "file":
|
| 309 |
+
fs.auto_mkdir = auto_mkdir
|
| 310 |
+
elif "r" not in mode and auto_mkdir:
|
| 311 |
+
parents = {fs._parent(path) for path in paths}
|
| 312 |
+
for parent in parents:
|
| 313 |
+
try:
|
| 314 |
+
fs.makedirs(parent, exist_ok=True)
|
| 315 |
+
except PermissionError:
|
| 316 |
+
pass
|
| 317 |
+
return OpenFiles(
|
| 318 |
+
[
|
| 319 |
+
OpenFile(
|
| 320 |
+
fs,
|
| 321 |
+
path,
|
| 322 |
+
mode=mode,
|
| 323 |
+
compression=compression,
|
| 324 |
+
encoding=encoding,
|
| 325 |
+
errors=errors,
|
| 326 |
+
newline=newline,
|
| 327 |
+
)
|
| 328 |
+
for path in paths
|
| 329 |
+
],
|
| 330 |
+
mode=mode,
|
| 331 |
+
fs=fs,
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def _un_chain(path, kwargs):
|
| 336 |
+
# Avoid a circular import
|
| 337 |
+
from fsspec.implementations.chained import ChainedFileSystem
|
| 338 |
+
|
| 339 |
+
if "::" in path:
|
| 340 |
+
x = re.compile(".*[^a-z]+.*") # test for non protocol-like single word
|
| 341 |
+
known_protocols = set(available_protocols())
|
| 342 |
+
bits = []
|
| 343 |
+
|
| 344 |
+
# split on '::', then ensure each bit has a protocol
|
| 345 |
+
for p in path.split("::"):
|
| 346 |
+
if p in known_protocols:
|
| 347 |
+
bits.append(p + "://")
|
| 348 |
+
elif "://" in p or x.match(p):
|
| 349 |
+
bits.append(p)
|
| 350 |
+
else:
|
| 351 |
+
bits.append(p + "://")
|
| 352 |
+
else:
|
| 353 |
+
bits = [path]
|
| 354 |
+
|
| 355 |
+
# [[url, protocol, kwargs], ...]
|
| 356 |
+
out = []
|
| 357 |
+
previous_bit = None
|
| 358 |
+
kwargs = kwargs.copy()
|
| 359 |
+
|
| 360 |
+
for bit in reversed(bits):
|
| 361 |
+
protocol = kwargs.pop("protocol", None) or split_protocol(bit)[0] or "file"
|
| 362 |
+
cls = get_filesystem_class(protocol)
|
| 363 |
+
extra_kwargs = cls._get_kwargs_from_urls(bit)
|
| 364 |
+
kws = kwargs.pop(protocol, {}).copy()
|
| 365 |
+
|
| 366 |
+
if bit is bits[0]:
|
| 367 |
+
kws.update(kwargs)
|
| 368 |
+
|
| 369 |
+
kw = dict(
|
| 370 |
+
**{k: v for k, v in extra_kwargs.items() if k not in kws or v != kws[k]},
|
| 371 |
+
**kws,
|
| 372 |
+
)
|
| 373 |
+
bit = cls._strip_protocol(bit)
|
| 374 |
+
|
| 375 |
+
if (
|
| 376 |
+
"target_protocol" not in kw
|
| 377 |
+
and issubclass(cls, ChainedFileSystem)
|
| 378 |
+
and not bit
|
| 379 |
+
):
|
| 380 |
+
# replace bit if we are chaining and no path given
|
| 381 |
+
bit = previous_bit
|
| 382 |
+
|
| 383 |
+
out.append((bit, protocol, kw))
|
| 384 |
+
previous_bit = bit
|
| 385 |
+
|
| 386 |
+
out.reverse()
|
| 387 |
+
return out
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def url_to_fs(url, **kwargs):
|
| 391 |
+
"""
|
| 392 |
+
Turn fully-qualified and potentially chained URL into filesystem instance
|
| 393 |
+
|
| 394 |
+
Parameters
|
| 395 |
+
----------
|
| 396 |
+
url : str
|
| 397 |
+
The fsspec-compatible URL
|
| 398 |
+
**kwargs: dict
|
| 399 |
+
Extra options that make sense to a particular storage connection, e.g.
|
| 400 |
+
host, port, username, password, etc.
|
| 401 |
+
|
| 402 |
+
Returns
|
| 403 |
+
-------
|
| 404 |
+
filesystem : FileSystem
|
| 405 |
+
The new filesystem discovered from ``url`` and created with
|
| 406 |
+
``**kwargs``.
|
| 407 |
+
urlpath : str
|
| 408 |
+
The file-systems-specific URL for ``url``.
|
| 409 |
+
"""
|
| 410 |
+
url = stringify_path(url)
|
| 411 |
+
# non-FS arguments that appear in fsspec.open()
|
| 412 |
+
# inspect could keep this in sync with open()'s signature
|
| 413 |
+
known_kwargs = {
|
| 414 |
+
"compression",
|
| 415 |
+
"encoding",
|
| 416 |
+
"errors",
|
| 417 |
+
"expand",
|
| 418 |
+
"mode",
|
| 419 |
+
"name_function",
|
| 420 |
+
"newline",
|
| 421 |
+
"num",
|
| 422 |
+
}
|
| 423 |
+
kwargs = {k: v for k, v in kwargs.items() if k not in known_kwargs}
|
| 424 |
+
chain = _un_chain(url, kwargs)
|
| 425 |
+
inkwargs = {}
|
| 426 |
+
# Reverse iterate the chain, creating a nested target_* structure
|
| 427 |
+
for i, ch in enumerate(reversed(chain)):
|
| 428 |
+
urls, protocol, kw = ch
|
| 429 |
+
if i == len(chain) - 1:
|
| 430 |
+
inkwargs = dict(**kw, **inkwargs)
|
| 431 |
+
continue
|
| 432 |
+
inkwargs["target_options"] = dict(**kw, **inkwargs)
|
| 433 |
+
inkwargs["target_protocol"] = protocol
|
| 434 |
+
inkwargs["fo"] = urls
|
| 435 |
+
urlpath, protocol, _ = chain[0]
|
| 436 |
+
fs = filesystem(protocol, **inkwargs)
|
| 437 |
+
return fs, urlpath
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
DEFAULT_EXPAND = conf.get("open_expand", False)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def open(
|
| 444 |
+
urlpath,
|
| 445 |
+
mode="rb",
|
| 446 |
+
compression=None,
|
| 447 |
+
encoding="utf8",
|
| 448 |
+
errors=None,
|
| 449 |
+
protocol=None,
|
| 450 |
+
newline=None,
|
| 451 |
+
expand=None,
|
| 452 |
+
**kwargs,
|
| 453 |
+
) -> OpenFile:
|
| 454 |
+
"""Given a path or paths, return one ``OpenFile`` object.
|
| 455 |
+
|
| 456 |
+
Parameters
|
| 457 |
+
----------
|
| 458 |
+
urlpath: string or list
|
| 459 |
+
Absolute or relative filepath. Prefix with a protocol like ``s3://``
|
| 460 |
+
to read from alternative filesystems. Should not include glob
|
| 461 |
+
character(s).
|
| 462 |
+
mode: 'rb', 'wt', etc.
|
| 463 |
+
compression: string or None
|
| 464 |
+
If given, open file using compression codec. Can either be a compression
|
| 465 |
+
name (a key in ``fsspec.compression.compr``) or "infer" to guess the
|
| 466 |
+
compression from the filename suffix.
|
| 467 |
+
encoding: str
|
| 468 |
+
For text mode only
|
| 469 |
+
errors: None or str
|
| 470 |
+
Passed to TextIOWrapper in text mode
|
| 471 |
+
protocol: str or None
|
| 472 |
+
If given, overrides the protocol found in the URL.
|
| 473 |
+
newline: bytes or None
|
| 474 |
+
Used for line terminator in text mode. If None, uses system default;
|
| 475 |
+
if blank, uses no translation.
|
| 476 |
+
expand: bool or None
|
| 477 |
+
Whether to regard file paths containing special glob characters as needing
|
| 478 |
+
expansion (finding the first match) or absolute. Setting False allows using
|
| 479 |
+
paths which do embed such characters. If None (default), this argument
|
| 480 |
+
takes its value from the DEFAULT_EXPAND module variable, which takes
|
| 481 |
+
its initial value from the "open_expand" config value at startup, which will
|
| 482 |
+
be False if not set.
|
| 483 |
+
**kwargs: dict
|
| 484 |
+
Extra options that make sense to a particular storage connection, e.g.
|
| 485 |
+
host, port, username, password, etc.
|
| 486 |
+
|
| 487 |
+
Examples
|
| 488 |
+
--------
|
| 489 |
+
>>> openfile = open('2015-01-01.csv') # doctest: +SKIP
|
| 490 |
+
>>> openfile = open(
|
| 491 |
+
... 's3://bucket/2015-01-01.csv.gz', compression='gzip'
|
| 492 |
+
... ) # doctest: +SKIP
|
| 493 |
+
>>> with openfile as f:
|
| 494 |
+
... df = pd.read_csv(f) # doctest: +SKIP
|
| 495 |
+
...
|
| 496 |
+
|
| 497 |
+
Returns
|
| 498 |
+
-------
|
| 499 |
+
``OpenFile`` object.
|
| 500 |
+
|
| 501 |
+
Notes
|
| 502 |
+
-----
|
| 503 |
+
For a full list of the available protocols and the implementations that
|
| 504 |
+
they map across to see the latest online documentation:
|
| 505 |
+
|
| 506 |
+
- For implementations built into ``fsspec`` see
|
| 507 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
|
| 508 |
+
- For implementations in separate packages see
|
| 509 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
|
| 510 |
+
"""
|
| 511 |
+
expand = DEFAULT_EXPAND if expand is None else expand
|
| 512 |
+
out = open_files(
|
| 513 |
+
urlpath=[urlpath],
|
| 514 |
+
mode=mode,
|
| 515 |
+
compression=compression,
|
| 516 |
+
encoding=encoding,
|
| 517 |
+
errors=errors,
|
| 518 |
+
protocol=protocol,
|
| 519 |
+
newline=newline,
|
| 520 |
+
expand=expand,
|
| 521 |
+
**kwargs,
|
| 522 |
+
)
|
| 523 |
+
if not out:
|
| 524 |
+
raise FileNotFoundError(urlpath)
|
| 525 |
+
return out[0]
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def open_local(
|
| 529 |
+
url: str | list[str] | Path | list[Path],
|
| 530 |
+
mode: str = "rb",
|
| 531 |
+
**storage_options: dict,
|
| 532 |
+
) -> str | list[str]:
|
| 533 |
+
"""Open file(s) which can be resolved to local
|
| 534 |
+
|
| 535 |
+
For files which either are local, or get downloaded upon open
|
| 536 |
+
(e.g., by file caching)
|
| 537 |
+
|
| 538 |
+
Parameters
|
| 539 |
+
----------
|
| 540 |
+
url: str or list(str)
|
| 541 |
+
mode: str
|
| 542 |
+
Must be read mode
|
| 543 |
+
storage_options:
|
| 544 |
+
passed on to FS for or used by open_files (e.g., compression)
|
| 545 |
+
"""
|
| 546 |
+
if "r" not in mode:
|
| 547 |
+
raise ValueError("Can only ensure local files when reading")
|
| 548 |
+
of = open_files(url, mode=mode, **storage_options)
|
| 549 |
+
if not getattr(of[0].fs, "local_file", False):
|
| 550 |
+
raise ValueError(
|
| 551 |
+
"open_local can only be used on a filesystem which"
|
| 552 |
+
" has attribute local_file=True"
|
| 553 |
+
)
|
| 554 |
+
with of as files:
|
| 555 |
+
paths = [f.name for f in files]
|
| 556 |
+
if (isinstance(url, str) and not has_magic(url)) or isinstance(url, Path):
|
| 557 |
+
return paths[0]
|
| 558 |
+
return paths
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def get_compression(urlpath, compression):
|
| 562 |
+
if compression == "infer":
|
| 563 |
+
compression = infer_compression(urlpath)
|
| 564 |
+
if compression is not None and compression not in compr:
|
| 565 |
+
raise ValueError(f"Compression type {compression} not supported")
|
| 566 |
+
return compression
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def split_protocol(urlpath):
|
| 570 |
+
"""Return protocol, path pair"""
|
| 571 |
+
urlpath = stringify_path(urlpath)
|
| 572 |
+
if "://" in urlpath:
|
| 573 |
+
protocol, path = urlpath.split("://", 1)
|
| 574 |
+
if len(protocol) > 1:
|
| 575 |
+
# excludes Windows paths
|
| 576 |
+
return protocol, path
|
| 577 |
+
if urlpath.startswith("data:"):
|
| 578 |
+
return urlpath.split(":", 1)
|
| 579 |
+
return None, urlpath
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def strip_protocol(urlpath):
|
| 583 |
+
"""Return only path part of full URL, according to appropriate backend"""
|
| 584 |
+
protocol, _ = split_protocol(urlpath)
|
| 585 |
+
cls = get_filesystem_class(protocol)
|
| 586 |
+
return cls._strip_protocol(urlpath)
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def expand_paths_if_needed(paths, mode, num, fs, name_function):
|
| 590 |
+
"""Expand paths if they have a ``*`` in them (write mode) or any of ``*?[]``
|
| 591 |
+
in them (read mode).
|
| 592 |
+
|
| 593 |
+
:param paths: list of paths
|
| 594 |
+
mode: str
|
| 595 |
+
Mode in which to open files.
|
| 596 |
+
num: int
|
| 597 |
+
If opening in writing mode, number of files we expect to create.
|
| 598 |
+
fs: filesystem object
|
| 599 |
+
name_function: callable
|
| 600 |
+
If opening in writing mode, this callable is used to generate path
|
| 601 |
+
names. Names are generated for each partition by
|
| 602 |
+
``urlpath.replace('*', name_function(partition_index))``.
|
| 603 |
+
:return: list of paths
|
| 604 |
+
"""
|
| 605 |
+
expanded_paths = []
|
| 606 |
+
paths = list(paths)
|
| 607 |
+
|
| 608 |
+
if "w" in mode or "x" in mode: # write mode
|
| 609 |
+
if sum(1 for p in paths if "*" in p) > 1:
|
| 610 |
+
raise ValueError(
|
| 611 |
+
"When writing data, only one filename mask can be specified."
|
| 612 |
+
)
|
| 613 |
+
num = max(num, len(paths))
|
| 614 |
+
|
| 615 |
+
for curr_path in paths:
|
| 616 |
+
if "*" in curr_path:
|
| 617 |
+
# expand using name_function
|
| 618 |
+
expanded_paths.extend(_expand_paths(curr_path, name_function, num))
|
| 619 |
+
else:
|
| 620 |
+
expanded_paths.append(curr_path)
|
| 621 |
+
# if we generated more paths that asked for, trim the list
|
| 622 |
+
if len(expanded_paths) > num:
|
| 623 |
+
expanded_paths = expanded_paths[:num]
|
| 624 |
+
|
| 625 |
+
else: # read mode
|
| 626 |
+
for curr_path in paths:
|
| 627 |
+
if has_magic(curr_path):
|
| 628 |
+
# expand using glob
|
| 629 |
+
expanded_paths.extend(fs.glob(curr_path))
|
| 630 |
+
else:
|
| 631 |
+
expanded_paths.append(curr_path)
|
| 632 |
+
|
| 633 |
+
return expanded_paths
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
def get_fs_token_paths(
|
| 637 |
+
urlpath,
|
| 638 |
+
mode="rb",
|
| 639 |
+
num=1,
|
| 640 |
+
name_function=None,
|
| 641 |
+
storage_options=None,
|
| 642 |
+
protocol=None,
|
| 643 |
+
expand=True,
|
| 644 |
+
):
|
| 645 |
+
"""Filesystem, deterministic token, and paths from a urlpath and options.
|
| 646 |
+
|
| 647 |
+
Parameters
|
| 648 |
+
----------
|
| 649 |
+
urlpath: string or iterable
|
| 650 |
+
Absolute or relative filepath, URL (may include protocols like
|
| 651 |
+
``s3://``), or globstring pointing to data.
|
| 652 |
+
mode: str, optional
|
| 653 |
+
Mode in which to open files.
|
| 654 |
+
num: int, optional
|
| 655 |
+
If opening in writing mode, number of files we expect to create.
|
| 656 |
+
name_function: callable, optional
|
| 657 |
+
If opening in writing mode, this callable is used to generate path
|
| 658 |
+
names. Names are generated for each partition by
|
| 659 |
+
``urlpath.replace('*', name_function(partition_index))``.
|
| 660 |
+
storage_options: dict, optional
|
| 661 |
+
Additional keywords to pass to the filesystem class.
|
| 662 |
+
protocol: str or None
|
| 663 |
+
To override the protocol specifier in the URL
|
| 664 |
+
expand: bool
|
| 665 |
+
Expand string paths for writing, assuming the path is a directory
|
| 666 |
+
"""
|
| 667 |
+
if isinstance(urlpath, (list, tuple, set)):
|
| 668 |
+
if not urlpath:
|
| 669 |
+
raise ValueError("empty urlpath sequence")
|
| 670 |
+
urlpath0 = stringify_path(next(iter(urlpath)))
|
| 671 |
+
else:
|
| 672 |
+
urlpath0 = stringify_path(urlpath)
|
| 673 |
+
storage_options = storage_options or {}
|
| 674 |
+
if protocol:
|
| 675 |
+
storage_options["protocol"] = protocol
|
| 676 |
+
chain = _un_chain(urlpath0, storage_options or {})
|
| 677 |
+
inkwargs = {}
|
| 678 |
+
# Reverse iterate the chain, creating a nested target_* structure
|
| 679 |
+
for i, ch in enumerate(reversed(chain)):
|
| 680 |
+
urls, nested_protocol, kw = ch
|
| 681 |
+
if i == len(chain) - 1:
|
| 682 |
+
inkwargs = dict(**kw, **inkwargs)
|
| 683 |
+
continue
|
| 684 |
+
inkwargs["target_options"] = dict(**kw, **inkwargs)
|
| 685 |
+
inkwargs["target_protocol"] = nested_protocol
|
| 686 |
+
inkwargs["fo"] = urls
|
| 687 |
+
paths, protocol, _ = chain[0]
|
| 688 |
+
fs = filesystem(protocol, **inkwargs)
|
| 689 |
+
if isinstance(urlpath, (list, tuple, set)):
|
| 690 |
+
pchains = [
|
| 691 |
+
_un_chain(stringify_path(u), storage_options or {})[0] for u in urlpath
|
| 692 |
+
]
|
| 693 |
+
if len({pc[1] for pc in pchains}) > 1:
|
| 694 |
+
raise ValueError(f"Protocol mismatch getting fs from {urlpath}")
|
| 695 |
+
paths = [pc[0] for pc in pchains]
|
| 696 |
+
else:
|
| 697 |
+
paths = fs._strip_protocol(paths)
|
| 698 |
+
if isinstance(paths, (list, tuple, set)):
|
| 699 |
+
if expand:
|
| 700 |
+
paths = expand_paths_if_needed(paths, mode, num, fs, name_function)
|
| 701 |
+
elif not isinstance(paths, list):
|
| 702 |
+
paths = list(paths)
|
| 703 |
+
else:
|
| 704 |
+
if ("w" in mode or "x" in mode) and expand:
|
| 705 |
+
paths = _expand_paths(paths, name_function, num)
|
| 706 |
+
elif "*" in paths:
|
| 707 |
+
paths = [f for f in sorted(fs.glob(paths)) if not fs.isdir(f)]
|
| 708 |
+
else:
|
| 709 |
+
paths = [paths]
|
| 710 |
+
|
| 711 |
+
return fs, fs._fs_token, paths
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
def _expand_paths(path, name_function, num):
|
| 715 |
+
if isinstance(path, str):
|
| 716 |
+
if path.count("*") > 1:
|
| 717 |
+
raise ValueError("Output path spec must contain exactly one '*'.")
|
| 718 |
+
elif "*" not in path:
|
| 719 |
+
# paths are "/"-separated on every filesystem, including local ones
|
| 720 |
+
path = posixpath.join(path, "*.part")
|
| 721 |
+
|
| 722 |
+
if name_function is None:
|
| 723 |
+
name_function = build_name_function(num - 1)
|
| 724 |
+
|
| 725 |
+
paths = [path.replace("*", name_function(i)) for i in range(num)]
|
| 726 |
+
if paths != sorted(paths):
|
| 727 |
+
logger.warning(
|
| 728 |
+
"In order to preserve order between partitions"
|
| 729 |
+
" paths created with ``name_function`` should "
|
| 730 |
+
"sort to partition order"
|
| 731 |
+
)
|
| 732 |
+
elif isinstance(path, (tuple, list)):
|
| 733 |
+
assert len(path) == num
|
| 734 |
+
paths = list(path)
|
| 735 |
+
else:
|
| 736 |
+
raise ValueError(
|
| 737 |
+
"Path should be either\n"
|
| 738 |
+
"1. A list of paths: ['foo.json', 'bar.json', ...]\n"
|
| 739 |
+
"2. A directory: 'foo/\n"
|
| 740 |
+
"3. A path with a '*' in it: 'foo.*.json'"
|
| 741 |
+
)
|
| 742 |
+
return paths
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
class PickleableTextIOWrapper(io.TextIOWrapper):
|
| 746 |
+
"""TextIOWrapper cannot be pickled. This solves it.
|
| 747 |
+
|
| 748 |
+
Requires that ``buffer`` be pickleable, which all instances of
|
| 749 |
+
AbstractBufferedFile are.
|
| 750 |
+
"""
|
| 751 |
+
|
| 752 |
+
def __init__(
|
| 753 |
+
self,
|
| 754 |
+
buffer,
|
| 755 |
+
encoding=None,
|
| 756 |
+
errors=None,
|
| 757 |
+
newline=None,
|
| 758 |
+
line_buffering=False,
|
| 759 |
+
write_through=False,
|
| 760 |
+
):
|
| 761 |
+
self.args = buffer, encoding, errors, newline, line_buffering, write_through
|
| 762 |
+
super().__init__(*self.args)
|
| 763 |
+
|
| 764 |
+
def __reduce__(self):
|
| 765 |
+
return PickleableTextIOWrapper, self.args
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/dircache.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from collections import OrderedDict
|
| 3 |
+
from collections.abc import MutableMapping
|
| 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 |
+
Parameters
|
| 36 |
+
----------
|
| 37 |
+
use_listings_cache: bool
|
| 38 |
+
If False, this cache never returns items, but always reports KeyError,
|
| 39 |
+
and setting items has no effect.
|
| 40 |
+
listings_expiry_time: int or float (optional)
|
| 41 |
+
Time in seconds that a listing is considered valid. If None,
|
| 42 |
+
listings do not expire. Time is measured from when the entry was set.
|
| 43 |
+
max_paths: int (optional)
|
| 44 |
+
The maximum number of directory listings to retain in the cache.
|
| 45 |
+
When the cache exceeds this limit, the least recently used
|
| 46 |
+
(set or accessed) listings are evicted. If None, 0, or negative,
|
| 47 |
+
there is no limit.
|
| 48 |
+
"""
|
| 49 |
+
# max_paths is normalized to be either positive or None.
|
| 50 |
+
self.max_paths = max_paths if max_paths and max_paths > 0 else None
|
| 51 |
+
self._cache = OrderedDict() if self.max_paths else {}
|
| 52 |
+
self._times = {}
|
| 53 |
+
self.use_listings_cache = use_listings_cache
|
| 54 |
+
self.listings_expiry_time = listings_expiry_time
|
| 55 |
+
|
| 56 |
+
def __getitem__(self, item):
|
| 57 |
+
if not self.use_listings_cache:
|
| 58 |
+
raise KeyError(item)
|
| 59 |
+
|
| 60 |
+
if self.listings_expiry_time is not None and item in self._cache:
|
| 61 |
+
if time.time() - self._times.get(item, 0) > self.listings_expiry_time:
|
| 62 |
+
del self[item]
|
| 63 |
+
raise KeyError(item)
|
| 64 |
+
|
| 65 |
+
val = self._cache[item]
|
| 66 |
+
if self.max_paths:
|
| 67 |
+
self._cache.move_to_end(item)
|
| 68 |
+
return val
|
| 69 |
+
|
| 70 |
+
def clear(self):
|
| 71 |
+
self._cache.clear()
|
| 72 |
+
self._times.clear()
|
| 73 |
+
|
| 74 |
+
def __len__(self):
|
| 75 |
+
return len(self._cache)
|
| 76 |
+
|
| 77 |
+
def __contains__(self, item):
|
| 78 |
+
if not self.use_listings_cache or item not in self._cache:
|
| 79 |
+
return False
|
| 80 |
+
|
| 81 |
+
if self.listings_expiry_time is not None:
|
| 82 |
+
if time.time() - self._times.get(item, 0) > self.listings_expiry_time:
|
| 83 |
+
del self[item]
|
| 84 |
+
return False
|
| 85 |
+
|
| 86 |
+
return True
|
| 87 |
+
|
| 88 |
+
def __setitem__(self, key, value):
|
| 89 |
+
if not self.use_listings_cache:
|
| 90 |
+
return
|
| 91 |
+
|
| 92 |
+
self._cache[key] = value
|
| 93 |
+
if self.listings_expiry_time is not None:
|
| 94 |
+
self._times[key] = time.time()
|
| 95 |
+
|
| 96 |
+
if self.max_paths:
|
| 97 |
+
self._cache.move_to_end(key)
|
| 98 |
+
if len(self._cache) > self.max_paths:
|
| 99 |
+
oldest, _ = self._cache.popitem(last=False)
|
| 100 |
+
self._times.pop(oldest, None)
|
| 101 |
+
|
| 102 |
+
def __delitem__(self, key):
|
| 103 |
+
del self._cache[key]
|
| 104 |
+
self._times.pop(key, None)
|
| 105 |
+
|
| 106 |
+
def __iter__(self):
|
| 107 |
+
if not self.use_listings_cache:
|
| 108 |
+
return
|
| 109 |
+
|
| 110 |
+
if self.listings_expiry_time is None:
|
| 111 |
+
yield from self._cache
|
| 112 |
+
return
|
| 113 |
+
|
| 114 |
+
now = time.time()
|
| 115 |
+
for key in list(self._cache):
|
| 116 |
+
if now - self._times.get(key, 0) > self.listings_expiry_time:
|
| 117 |
+
del self[key]
|
| 118 |
+
else:
|
| 119 |
+
yield key
|
| 120 |
+
|
| 121 |
+
def __reduce__(self):
|
| 122 |
+
return (
|
| 123 |
+
DirCache,
|
| 124 |
+
(self.use_listings_cache, self.listings_expiry_time, self.max_paths),
|
| 125 |
+
)
|
tasks/tasksmith-3bb3c78392c6/tests/source/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 |
+
"""
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/fuse.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_true",
|
| 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:])
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/generic.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
import os
|
| 6 |
+
import uuid
|
| 7 |
+
|
| 8 |
+
from .asyn import AsyncFileSystem, _run_coros_in_chunks, sync_wrapper
|
| 9 |
+
from .callbacks import DEFAULT_CALLBACK
|
| 10 |
+
from .core import filesystem, get_filesystem_class, split_protocol, url_to_fs
|
| 11 |
+
from .utils import check_contained
|
| 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 |
+
# The names came from the source listing; ".." in one of them would
|
| 99 |
+
# otherwise place the copy above the destination.
|
| 100 |
+
check_contained(destination, [a.replace(source, destination, 1) for a in allfiles])
|
| 101 |
+
otherfiles = fs.find(destination, withdirs=True, detail=True)
|
| 102 |
+
dirs = [
|
| 103 |
+
a
|
| 104 |
+
for a, v in allfiles.items()
|
| 105 |
+
if v["type"] == "directory"
|
| 106 |
+
and a.replace(source, destination, 1) not in otherfiles
|
| 107 |
+
]
|
| 108 |
+
logger.debug(f"{len(dirs)} directories to create")
|
| 109 |
+
if dirs:
|
| 110 |
+
fs.make_many_dirs(
|
| 111 |
+
[dirn.replace(source, destination, 1) for dirn in dirs], exist_ok=True
|
| 112 |
+
)
|
| 113 |
+
allfiles = {a: v for a, v in allfiles.items() if v["type"] == "file"}
|
| 114 |
+
logger.debug(f"{len(allfiles)} files to consider for copy")
|
| 115 |
+
to_delete = [
|
| 116 |
+
o
|
| 117 |
+
for o, v in otherfiles.items()
|
| 118 |
+
if o.replace(destination, source, 1) not in allfiles and v["type"] == "file"
|
| 119 |
+
]
|
| 120 |
+
for k, v in allfiles.copy().items():
|
| 121 |
+
otherfile = k.replace(source, destination, 1)
|
| 122 |
+
if otherfile in otherfiles:
|
| 123 |
+
if update_cond == "always":
|
| 124 |
+
allfiles[k] = otherfile
|
| 125 |
+
elif update_cond == "never":
|
| 126 |
+
allfiles.pop(k)
|
| 127 |
+
elif update_cond == "different":
|
| 128 |
+
inf1 = source_field(v) if callable(source_field) else v[source_field]
|
| 129 |
+
v2 = otherfiles[otherfile]
|
| 130 |
+
inf2 = dest_field(v2) if callable(dest_field) else v2[dest_field]
|
| 131 |
+
if inf1 != inf2:
|
| 132 |
+
# details mismatch, make copy
|
| 133 |
+
allfiles[k] = otherfile
|
| 134 |
+
else:
|
| 135 |
+
# details match, don't copy
|
| 136 |
+
allfiles.pop(k)
|
| 137 |
+
else:
|
| 138 |
+
# file not in target yet
|
| 139 |
+
allfiles[k] = otherfile
|
| 140 |
+
logger.debug(f"{len(allfiles)} files to copy")
|
| 141 |
+
if allfiles:
|
| 142 |
+
source_files, target_files = zip(*allfiles.items())
|
| 143 |
+
fs.cp(source_files, target_files, **kwargs)
|
| 144 |
+
logger.debug(f"{len(to_delete)} files to delete")
|
| 145 |
+
if delete_missing and to_delete:
|
| 146 |
+
fs.rm(to_delete)
|
| 147 |
+
return allfiles
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class GenericFileSystem(AsyncFileSystem):
|
| 151 |
+
"""Wrapper over all other FS types
|
| 152 |
+
|
| 153 |
+
<experimental!>
|
| 154 |
+
|
| 155 |
+
This implementation is a single unified interface to be able to run FS operations
|
| 156 |
+
over generic URLs, and dispatch to the specific implementations using the URL
|
| 157 |
+
protocol prefix.
|
| 158 |
+
|
| 159 |
+
Note: instances of this FS are always async, even if you never use it with any async
|
| 160 |
+
backend.
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
protocol = "generic" # there is no real reason to ever use a protocol with this FS
|
| 164 |
+
|
| 165 |
+
def __init__(self, default_method="default", storage_options=None, **kwargs):
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
Parameters
|
| 169 |
+
----------
|
| 170 |
+
default_method: str (optional)
|
| 171 |
+
Defines how to configure backend FS instances. Options are:
|
| 172 |
+
- "default": instantiate like FSClass(), with no
|
| 173 |
+
extra arguments; this is the default instance of that FS, and can be
|
| 174 |
+
configured via the config system
|
| 175 |
+
- "generic": takes instances from the `_generic_fs` dict in this module,
|
| 176 |
+
which you must populate before use. Keys are by protocol
|
| 177 |
+
- "options": expects storage_options, a dict mapping protocol to
|
| 178 |
+
kwargs to use when constructing the filesystem
|
| 179 |
+
- "current": takes the most recently instantiated version of each FS
|
| 180 |
+
"""
|
| 181 |
+
self.method = default_method
|
| 182 |
+
self.st_opts = storage_options
|
| 183 |
+
super().__init__(**kwargs)
|
| 184 |
+
|
| 185 |
+
def _parent(self, path):
|
| 186 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 187 |
+
return fs.unstrip_protocol(fs._parent(path))
|
| 188 |
+
|
| 189 |
+
def _strip_protocol(self, path):
|
| 190 |
+
# normalization only
|
| 191 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 192 |
+
return fs.unstrip_protocol(fs._strip_protocol(path))
|
| 193 |
+
|
| 194 |
+
async def _find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
|
| 195 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 196 |
+
if fs.async_impl:
|
| 197 |
+
out = await fs._find(
|
| 198 |
+
path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs
|
| 199 |
+
)
|
| 200 |
+
else:
|
| 201 |
+
out = fs.find(
|
| 202 |
+
path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs
|
| 203 |
+
)
|
| 204 |
+
result = {}
|
| 205 |
+
for k, v in out.items():
|
| 206 |
+
v = v.copy() # don't corrupt target FS dircache
|
| 207 |
+
name = fs.unstrip_protocol(k)
|
| 208 |
+
v["name"] = name
|
| 209 |
+
result[name] = v
|
| 210 |
+
if detail:
|
| 211 |
+
return result
|
| 212 |
+
return list(result)
|
| 213 |
+
|
| 214 |
+
async def _info(self, url, **kwargs):
|
| 215 |
+
fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
|
| 216 |
+
if fs.async_impl:
|
| 217 |
+
out = await fs._info(url, **kwargs)
|
| 218 |
+
else:
|
| 219 |
+
out = fs.info(url, **kwargs)
|
| 220 |
+
out = out.copy() # don't edit originals
|
| 221 |
+
out["name"] = fs.unstrip_protocol(out["name"])
|
| 222 |
+
return out
|
| 223 |
+
|
| 224 |
+
async def _ls(
|
| 225 |
+
self,
|
| 226 |
+
url,
|
| 227 |
+
detail=True,
|
| 228 |
+
**kwargs,
|
| 229 |
+
):
|
| 230 |
+
fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
|
| 231 |
+
if fs.async_impl:
|
| 232 |
+
out = await fs._ls(url, detail=True, **kwargs)
|
| 233 |
+
else:
|
| 234 |
+
out = fs.ls(url, detail=True, **kwargs)
|
| 235 |
+
out = [o.copy() for o in out] # don't edit originals
|
| 236 |
+
for o in out:
|
| 237 |
+
o["name"] = fs.unstrip_protocol(o["name"])
|
| 238 |
+
if detail:
|
| 239 |
+
return out
|
| 240 |
+
else:
|
| 241 |
+
return [o["name"] for o in out]
|
| 242 |
+
|
| 243 |
+
async def _cat_file(
|
| 244 |
+
self,
|
| 245 |
+
url,
|
| 246 |
+
**kwargs,
|
| 247 |
+
):
|
| 248 |
+
fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
|
| 249 |
+
if fs.async_impl:
|
| 250 |
+
return await fs._cat_file(url, **kwargs)
|
| 251 |
+
else:
|
| 252 |
+
return fs.cat_file(url, **kwargs)
|
| 253 |
+
|
| 254 |
+
async def _pipe_file(
|
| 255 |
+
self,
|
| 256 |
+
path,
|
| 257 |
+
value,
|
| 258 |
+
**kwargs,
|
| 259 |
+
):
|
| 260 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 261 |
+
if fs.async_impl:
|
| 262 |
+
return await fs._pipe_file(path, value, **kwargs)
|
| 263 |
+
else:
|
| 264 |
+
return fs.pipe_file(path, value, **kwargs)
|
| 265 |
+
|
| 266 |
+
async def _rm(self, url, **kwargs):
|
| 267 |
+
urls = url
|
| 268 |
+
if isinstance(urls, str):
|
| 269 |
+
urls = [urls]
|
| 270 |
+
fs = _resolve_fs(urls[0], self.method, storage_options=self.st_opts)
|
| 271 |
+
if fs.async_impl:
|
| 272 |
+
await fs._rm(urls, **kwargs)
|
| 273 |
+
else:
|
| 274 |
+
fs.rm(url, **kwargs)
|
| 275 |
+
|
| 276 |
+
async def _makedirs(self, path, exist_ok=False):
|
| 277 |
+
logger.debug("Make dir %s", path)
|
| 278 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 279 |
+
if fs.async_impl:
|
| 280 |
+
await fs._makedirs(path, exist_ok=exist_ok)
|
| 281 |
+
else:
|
| 282 |
+
fs.makedirs(path, exist_ok=exist_ok)
|
| 283 |
+
|
| 284 |
+
def rsync(self, source, destination, **kwargs):
|
| 285 |
+
"""Sync files between two directory trees
|
| 286 |
+
|
| 287 |
+
See `func:rsync` for more details.
|
| 288 |
+
"""
|
| 289 |
+
rsync(source, destination, fs=self, **kwargs)
|
| 290 |
+
|
| 291 |
+
async def _cp_file(
|
| 292 |
+
self,
|
| 293 |
+
url,
|
| 294 |
+
url2,
|
| 295 |
+
blocksize=2**20,
|
| 296 |
+
callback=DEFAULT_CALLBACK,
|
| 297 |
+
tempdir: str | None = None,
|
| 298 |
+
**kwargs,
|
| 299 |
+
):
|
| 300 |
+
fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
|
| 301 |
+
fs2 = _resolve_fs(url2, self.method, storage_options=self.st_opts)
|
| 302 |
+
if fs is fs2:
|
| 303 |
+
# pure remote
|
| 304 |
+
if fs.async_impl:
|
| 305 |
+
return await fs._copy(url, url2, **kwargs)
|
| 306 |
+
else:
|
| 307 |
+
return fs.copy(url, url2, **kwargs)
|
| 308 |
+
await copy_file_op(fs, [url], fs2, [url2], tempdir, 1, on_error="raise")
|
| 309 |
+
|
| 310 |
+
async def _make_many_dirs(self, urls, exist_ok=True):
|
| 311 |
+
fs = _resolve_fs(urls[0], self.method, storage_options=self.st_opts)
|
| 312 |
+
if fs.async_impl:
|
| 313 |
+
coros = [fs._makedirs(u, exist_ok=exist_ok) for u in urls]
|
| 314 |
+
await _run_coros_in_chunks(coros)
|
| 315 |
+
else:
|
| 316 |
+
for u in urls:
|
| 317 |
+
fs.makedirs(u, exist_ok=exist_ok)
|
| 318 |
+
|
| 319 |
+
make_many_dirs = sync_wrapper(_make_many_dirs)
|
| 320 |
+
|
| 321 |
+
async def _copy(
|
| 322 |
+
self,
|
| 323 |
+
path1: list[str],
|
| 324 |
+
path2: list[str],
|
| 325 |
+
recursive: bool = False,
|
| 326 |
+
on_error: str = "ignore",
|
| 327 |
+
maxdepth: int | None = None,
|
| 328 |
+
batch_size: int | None = None,
|
| 329 |
+
tempdir: str | None = None,
|
| 330 |
+
**kwargs,
|
| 331 |
+
):
|
| 332 |
+
# TODO: special case for one FS being local, which can use get/put
|
| 333 |
+
# TODO: special case for one being memFS, which can use cat/pipe
|
| 334 |
+
if recursive:
|
| 335 |
+
raise NotImplementedError("Please use fsspec.generic.rsync")
|
| 336 |
+
path1 = [path1] if isinstance(path1, str) else path1
|
| 337 |
+
path2 = [path2] if isinstance(path2, str) else path2
|
| 338 |
+
|
| 339 |
+
fs = _resolve_fs(path1, self.method, storage_options=self.st_opts)
|
| 340 |
+
fs2 = _resolve_fs(path2, self.method, storage_options=self.st_opts)
|
| 341 |
+
|
| 342 |
+
# Validate both entire batches before copying any files.
|
| 343 |
+
for paths, backend, side in (
|
| 344 |
+
(path1, fs, "source"),
|
| 345 |
+
(path2, fs2, "destination"),
|
| 346 |
+
):
|
| 347 |
+
if any(
|
| 348 |
+
_resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 349 |
+
is not backend
|
| 350 |
+
for path in paths
|
| 351 |
+
):
|
| 352 |
+
raise ValueError(f"Multiple {side} backends are not supported")
|
| 353 |
+
|
| 354 |
+
if fs is fs2:
|
| 355 |
+
if fs.async_impl:
|
| 356 |
+
return await fs._copy(path1, path2, **kwargs)
|
| 357 |
+
else:
|
| 358 |
+
return fs.copy(path1, path2, **kwargs)
|
| 359 |
+
|
| 360 |
+
await copy_file_op(
|
| 361 |
+
fs, path1, fs2, path2, tempdir, batch_size, on_error=on_error
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
async def copy_file_op(
|
| 366 |
+
fs1, url1, fs2, url2, tempdir=None, batch_size=20, on_error="ignore"
|
| 367 |
+
):
|
| 368 |
+
import tempfile
|
| 369 |
+
|
| 370 |
+
with tempfile.TemporaryDirectory(dir=tempdir) as tempdir:
|
| 371 |
+
coros = [
|
| 372 |
+
_copy_file_op(
|
| 373 |
+
fs1,
|
| 374 |
+
u1,
|
| 375 |
+
fs2,
|
| 376 |
+
u2,
|
| 377 |
+
os.path.join(tempdir, uuid.uuid4().hex),
|
| 378 |
+
)
|
| 379 |
+
for u1, u2 in zip(url1, url2)
|
| 380 |
+
]
|
| 381 |
+
out = await _run_coros_in_chunks(
|
| 382 |
+
coros, batch_size=batch_size, return_exceptions=True
|
| 383 |
+
)
|
| 384 |
+
if on_error == "return":
|
| 385 |
+
return out
|
| 386 |
+
elif on_error == "raise":
|
| 387 |
+
for o in out:
|
| 388 |
+
if isinstance(o, Exception):
|
| 389 |
+
raise o
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
async def _copy_file_op(fs1, url1, fs2, url2, local, on_error="ignore"):
|
| 393 |
+
if fs1.async_impl:
|
| 394 |
+
await fs1._get_file(url1, local)
|
| 395 |
+
else:
|
| 396 |
+
fs1.get_file(url1, local)
|
| 397 |
+
if fs2.async_impl:
|
| 398 |
+
await fs2._put_file(local, url2)
|
| 399 |
+
else:
|
| 400 |
+
fs2.put_file(local, url2)
|
| 401 |
+
os.unlink(local)
|
| 402 |
+
logger.debug("Copy %s -> %s; done", url1, url2)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
async def maybe_await(cor):
|
| 406 |
+
if inspect.iscoroutine(cor):
|
| 407 |
+
return await cor
|
| 408 |
+
else:
|
| 409 |
+
return cor
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/gui.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/arrow.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import errno
|
| 2 |
+
import io
|
| 3 |
+
import os
|
| 4 |
+
import secrets
|
| 5 |
+
import shutil
|
| 6 |
+
from contextlib import suppress
|
| 7 |
+
from functools import cached_property, wraps
|
| 8 |
+
from urllib.parse import parse_qs
|
| 9 |
+
|
| 10 |
+
from fsspec.spec import AbstractFileSystem
|
| 11 |
+
from fsspec.utils import (
|
| 12 |
+
get_package_version_without_import,
|
| 13 |
+
infer_storage_options,
|
| 14 |
+
mirror_from,
|
| 15 |
+
tokenize,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def wrap_exceptions(func):
|
| 20 |
+
@wraps(func)
|
| 21 |
+
def wrapper(*args, **kwargs):
|
| 22 |
+
try:
|
| 23 |
+
return func(*args, **kwargs)
|
| 24 |
+
except OSError as exception:
|
| 25 |
+
if not exception.args:
|
| 26 |
+
raise
|
| 27 |
+
|
| 28 |
+
message, *args = exception.args
|
| 29 |
+
if isinstance(message, str) and "does not exist" in message:
|
| 30 |
+
raise FileNotFoundError(errno.ENOENT, message) from exception
|
| 31 |
+
else:
|
| 32 |
+
raise
|
| 33 |
+
|
| 34 |
+
return wrapper
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
PYARROW_VERSION = None
|
| 38 |
+
_EMPTY_ROOT_MARKER_FILESYSTEMS = {"gcs", "s3"}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ArrowFSWrapper(AbstractFileSystem):
|
| 42 |
+
"""FSSpec-compatible wrapper of pyarrow.fs.FileSystem.
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
----------
|
| 46 |
+
fs : pyarrow.fs.FileSystem
|
| 47 |
+
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
root_marker = "/"
|
| 51 |
+
|
| 52 |
+
def __init__(self, fs, **kwargs):
|
| 53 |
+
global PYARROW_VERSION
|
| 54 |
+
PYARROW_VERSION = get_package_version_without_import("pyarrow")
|
| 55 |
+
self.fs = fs
|
| 56 |
+
if fs.type_name in _EMPTY_ROOT_MARKER_FILESYSTEMS:
|
| 57 |
+
self.root_marker = ""
|
| 58 |
+
super().__init__(**kwargs)
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def protocol(self):
|
| 62 |
+
return self.fs.type_name
|
| 63 |
+
|
| 64 |
+
@cached_property
|
| 65 |
+
def fsid(self):
|
| 66 |
+
return "hdfs_" + tokenize(self.fs.host, self.fs.port)
|
| 67 |
+
|
| 68 |
+
def _parent(self, path):
|
| 69 |
+
if self.root_marker:
|
| 70 |
+
return super()._parent(path)
|
| 71 |
+
|
| 72 |
+
path = self._strip_protocol(path).lstrip("/")
|
| 73 |
+
return path.rsplit("/", 1)[0] if "/" in path else ""
|
| 74 |
+
|
| 75 |
+
@classmethod
|
| 76 |
+
def _strip_protocol(cls, path):
|
| 77 |
+
ops = infer_storage_options(path)
|
| 78 |
+
path = ops["path"]
|
| 79 |
+
if path.startswith("//"):
|
| 80 |
+
# special case for "hdfs://path" (without the triple slash)
|
| 81 |
+
path = path[1:]
|
| 82 |
+
return path
|
| 83 |
+
|
| 84 |
+
def ls(self, path, detail=False, **kwargs):
|
| 85 |
+
path = self._strip_protocol(path)
|
| 86 |
+
from pyarrow.fs import FileSelector
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
entries = [
|
| 90 |
+
self._make_entry(entry)
|
| 91 |
+
for entry in self.fs.get_file_info(FileSelector(path))
|
| 92 |
+
]
|
| 93 |
+
except (FileNotFoundError, NotADirectoryError):
|
| 94 |
+
entries = [self.info(path, **kwargs)]
|
| 95 |
+
if detail:
|
| 96 |
+
return entries
|
| 97 |
+
else:
|
| 98 |
+
return [entry["name"] for entry in entries]
|
| 99 |
+
|
| 100 |
+
def info(self, path, **kwargs):
|
| 101 |
+
path = self._strip_protocol(path)
|
| 102 |
+
[info] = self.fs.get_file_info([path])
|
| 103 |
+
return self._make_entry(info)
|
| 104 |
+
|
| 105 |
+
def exists(self, path):
|
| 106 |
+
path = self._strip_protocol(path)
|
| 107 |
+
try:
|
| 108 |
+
self.info(path)
|
| 109 |
+
except FileNotFoundError:
|
| 110 |
+
return False
|
| 111 |
+
else:
|
| 112 |
+
return True
|
| 113 |
+
|
| 114 |
+
def _make_entry(self, info):
|
| 115 |
+
from pyarrow.fs import FileType
|
| 116 |
+
|
| 117 |
+
if info.type is FileType.Directory:
|
| 118 |
+
kind = "directory"
|
| 119 |
+
elif info.type is FileType.File:
|
| 120 |
+
kind = "file"
|
| 121 |
+
elif info.type is FileType.NotFound:
|
| 122 |
+
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), info.path)
|
| 123 |
+
else:
|
| 124 |
+
kind = "other"
|
| 125 |
+
|
| 126 |
+
return {
|
| 127 |
+
"name": info.path,
|
| 128 |
+
"size": info.size,
|
| 129 |
+
"type": kind,
|
| 130 |
+
"mtime": info.mtime,
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
@wrap_exceptions
|
| 134 |
+
def cp_file(self, path1, path2, **kwargs):
|
| 135 |
+
path1 = self._strip_protocol(path1).rstrip("/")
|
| 136 |
+
path2 = self._strip_protocol(path2).rstrip("/")
|
| 137 |
+
|
| 138 |
+
with self._open(path1, "rb") as lstream:
|
| 139 |
+
tmp_fname = f"{path2}.tmp.{secrets.token_hex(6)}"
|
| 140 |
+
try:
|
| 141 |
+
with self.open(tmp_fname, "wb") as rstream:
|
| 142 |
+
shutil.copyfileobj(lstream, rstream)
|
| 143 |
+
self.fs.move(tmp_fname, path2)
|
| 144 |
+
except BaseException:
|
| 145 |
+
with suppress(FileNotFoundError):
|
| 146 |
+
self.fs.delete_file(tmp_fname)
|
| 147 |
+
raise
|
| 148 |
+
|
| 149 |
+
@wrap_exceptions
|
| 150 |
+
def mv(self, path1, path2, **kwargs):
|
| 151 |
+
path1 = self._strip_protocol(path1).rstrip("/")
|
| 152 |
+
path2 = self._strip_protocol(path2).rstrip("/")
|
| 153 |
+
self.fs.move(path1, path2)
|
| 154 |
+
|
| 155 |
+
@wrap_exceptions
|
| 156 |
+
def rm_file(self, path):
|
| 157 |
+
path = self._strip_protocol(path)
|
| 158 |
+
self.fs.delete_file(path)
|
| 159 |
+
|
| 160 |
+
@wrap_exceptions
|
| 161 |
+
def rm(self, path, recursive=False, maxdepth=None):
|
| 162 |
+
path = self._strip_protocol(path).rstrip("/")
|
| 163 |
+
if self.isdir(path):
|
| 164 |
+
if recursive:
|
| 165 |
+
self.fs.delete_dir(path)
|
| 166 |
+
else:
|
| 167 |
+
raise ValueError("Can't delete directories without recursive=False")
|
| 168 |
+
else:
|
| 169 |
+
self.fs.delete_file(path)
|
| 170 |
+
|
| 171 |
+
@wrap_exceptions
|
| 172 |
+
def _open(self, path, mode="rb", block_size=None, seekable=True, **kwargs):
|
| 173 |
+
if mode == "rb":
|
| 174 |
+
if seekable:
|
| 175 |
+
method = self.fs.open_input_file
|
| 176 |
+
else:
|
| 177 |
+
method = self.fs.open_input_stream
|
| 178 |
+
elif mode == "wb":
|
| 179 |
+
method = self.fs.open_output_stream
|
| 180 |
+
elif mode == "ab":
|
| 181 |
+
method = self.fs.open_append_stream
|
| 182 |
+
else:
|
| 183 |
+
raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}")
|
| 184 |
+
|
| 185 |
+
_kwargs = {}
|
| 186 |
+
if mode != "rb" or not seekable:
|
| 187 |
+
if int(PYARROW_VERSION.split(".")[0]) >= 4:
|
| 188 |
+
# disable compression auto-detection
|
| 189 |
+
_kwargs["compression"] = None
|
| 190 |
+
stream = method(path, **_kwargs)
|
| 191 |
+
|
| 192 |
+
return ArrowFile(self, stream, path, mode, block_size, **kwargs)
|
| 193 |
+
|
| 194 |
+
@wrap_exceptions
|
| 195 |
+
def mkdir(self, path, create_parents=True, **kwargs):
|
| 196 |
+
path = self._strip_protocol(path)
|
| 197 |
+
if create_parents:
|
| 198 |
+
self.makedirs(path, exist_ok=True)
|
| 199 |
+
else:
|
| 200 |
+
self.fs.create_dir(path, recursive=False)
|
| 201 |
+
|
| 202 |
+
@wrap_exceptions
|
| 203 |
+
def makedirs(self, path, exist_ok=False):
|
| 204 |
+
path = self._strip_protocol(path)
|
| 205 |
+
self.fs.create_dir(path, recursive=True)
|
| 206 |
+
|
| 207 |
+
@wrap_exceptions
|
| 208 |
+
def rmdir(self, path):
|
| 209 |
+
path = self._strip_protocol(path)
|
| 210 |
+
self.fs.delete_dir(path)
|
| 211 |
+
|
| 212 |
+
@wrap_exceptions
|
| 213 |
+
def modified(self, path):
|
| 214 |
+
path = self._strip_protocol(path)
|
| 215 |
+
return self.fs.get_file_info(path).mtime
|
| 216 |
+
|
| 217 |
+
def cat_file(self, path, start=None, end=None, **kwargs):
|
| 218 |
+
kwargs.setdefault("seekable", start not in [None, 0])
|
| 219 |
+
return super().cat_file(path, start, end, **kwargs)
|
| 220 |
+
|
| 221 |
+
def get_file(self, rpath, lpath, **kwargs):
|
| 222 |
+
kwargs.setdefault("seekable", False)
|
| 223 |
+
super().get_file(rpath, lpath, **kwargs)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@mirror_from(
|
| 227 |
+
"stream",
|
| 228 |
+
[
|
| 229 |
+
"read",
|
| 230 |
+
"readinto",
|
| 231 |
+
"seek",
|
| 232 |
+
"tell",
|
| 233 |
+
"write",
|
| 234 |
+
"flush",
|
| 235 |
+
"readable",
|
| 236 |
+
"writable",
|
| 237 |
+
"close",
|
| 238 |
+
"seekable",
|
| 239 |
+
],
|
| 240 |
+
)
|
| 241 |
+
class ArrowFile(io.IOBase):
|
| 242 |
+
def __init__(self, fs, stream, path, mode, block_size=None, **kwargs):
|
| 243 |
+
self.path = path
|
| 244 |
+
self.mode = mode
|
| 245 |
+
|
| 246 |
+
self.fs = fs
|
| 247 |
+
self.stream = stream
|
| 248 |
+
|
| 249 |
+
self.blocksize = self.block_size = block_size
|
| 250 |
+
self.kwargs = kwargs
|
| 251 |
+
|
| 252 |
+
def __enter__(self):
|
| 253 |
+
return self
|
| 254 |
+
|
| 255 |
+
@property
|
| 256 |
+
def closed(self):
|
| 257 |
+
return self.stream.closed
|
| 258 |
+
|
| 259 |
+
@property
|
| 260 |
+
def size(self):
|
| 261 |
+
if self.stream.seekable():
|
| 262 |
+
return self.stream.size()
|
| 263 |
+
return None
|
| 264 |
+
|
| 265 |
+
def __exit__(self, *args):
|
| 266 |
+
return self.close()
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class HadoopFileSystem(ArrowFSWrapper):
|
| 270 |
+
"""A wrapper on top of the pyarrow.fs.HadoopFileSystem
|
| 271 |
+
to connect it's interface with fsspec"""
|
| 272 |
+
|
| 273 |
+
protocol = "hdfs"
|
| 274 |
+
|
| 275 |
+
def __init__(
|
| 276 |
+
self,
|
| 277 |
+
host="default",
|
| 278 |
+
port=0,
|
| 279 |
+
user=None,
|
| 280 |
+
kerb_ticket=None,
|
| 281 |
+
replication=3,
|
| 282 |
+
extra_conf=None,
|
| 283 |
+
**kwargs,
|
| 284 |
+
):
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
Parameters
|
| 288 |
+
----------
|
| 289 |
+
host: str
|
| 290 |
+
Hostname, IP or "default" to try to read from Hadoop config
|
| 291 |
+
port: int
|
| 292 |
+
Port to connect on, or default from Hadoop config if 0
|
| 293 |
+
user: str or None
|
| 294 |
+
If given, connect as this username
|
| 295 |
+
kerb_ticket: str or None
|
| 296 |
+
If given, use this ticket for authentication
|
| 297 |
+
replication: int
|
| 298 |
+
set replication factor of file for write operations. default value is 3.
|
| 299 |
+
extra_conf: None or dict
|
| 300 |
+
Passed on to HadoopFileSystem
|
| 301 |
+
"""
|
| 302 |
+
from pyarrow.fs import HadoopFileSystem
|
| 303 |
+
|
| 304 |
+
fs = HadoopFileSystem(
|
| 305 |
+
host=host,
|
| 306 |
+
port=port,
|
| 307 |
+
user=user,
|
| 308 |
+
kerb_ticket=kerb_ticket,
|
| 309 |
+
replication=replication,
|
| 310 |
+
extra_conf=extra_conf,
|
| 311 |
+
)
|
| 312 |
+
super().__init__(fs=fs, **kwargs)
|
| 313 |
+
self._fsid = "hdfs_" + tokenize(host, port)
|
| 314 |
+
|
| 315 |
+
@property
|
| 316 |
+
def fsid(self):
|
| 317 |
+
return self._fsid
|
| 318 |
+
|
| 319 |
+
@staticmethod
|
| 320 |
+
def _get_kwargs_from_urls(path):
|
| 321 |
+
ops = infer_storage_options(path)
|
| 322 |
+
out = {}
|
| 323 |
+
if ops.get("host", None):
|
| 324 |
+
out["host"] = ops["host"]
|
| 325 |
+
if ops.get("username", None):
|
| 326 |
+
out["user"] = ops["username"]
|
| 327 |
+
if ops.get("port", None):
|
| 328 |
+
out["port"] = ops["port"]
|
| 329 |
+
if ops.get("url_query", None):
|
| 330 |
+
queries = parse_qs(ops["url_query"])
|
| 331 |
+
if queries.get("replication", None):
|
| 332 |
+
out["replication"] = int(queries["replication"][0])
|
| 333 |
+
return out
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/asyn_wrapper.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import functools
|
| 3 |
+
import inspect
|
| 4 |
+
|
| 5 |
+
import fsspec
|
| 6 |
+
from fsspec.asyn import AsyncFileSystem, running_async
|
| 7 |
+
|
| 8 |
+
from .chained import ChainedFileSystem
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def async_wrapper(func, obj=None, semaphore=None):
|
| 12 |
+
"""
|
| 13 |
+
Wraps a synchronous function to make it awaitable.
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
----------
|
| 17 |
+
func : callable
|
| 18 |
+
The synchronous function to wrap.
|
| 19 |
+
obj : object, optional
|
| 20 |
+
The instance to bind the function to, if applicable.
|
| 21 |
+
semaphore : asyncio.Semaphore, optional
|
| 22 |
+
A semaphore to limit concurrent calls.
|
| 23 |
+
|
| 24 |
+
Returns
|
| 25 |
+
-------
|
| 26 |
+
coroutine
|
| 27 |
+
An awaitable version of the function.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
@functools.wraps(func)
|
| 31 |
+
async def wrapper(*args, **kwargs):
|
| 32 |
+
if semaphore:
|
| 33 |
+
async with semaphore:
|
| 34 |
+
return await asyncio.to_thread(func, *args, **kwargs)
|
| 35 |
+
return await asyncio.to_thread(func, *args, **kwargs)
|
| 36 |
+
|
| 37 |
+
return wrapper
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class AsyncFileSystemWrapper(AsyncFileSystem, ChainedFileSystem):
|
| 41 |
+
"""
|
| 42 |
+
A wrapper class to convert a synchronous filesystem into an asynchronous one.
|
| 43 |
+
|
| 44 |
+
This class takes an existing synchronous filesystem implementation and wraps all
|
| 45 |
+
its methods to provide an asynchronous interface.
|
| 46 |
+
|
| 47 |
+
Parameters
|
| 48 |
+
----------
|
| 49 |
+
sync_fs : AbstractFileSystem
|
| 50 |
+
The synchronous filesystem instance to wrap.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
protocol = "asyncwrapper", "async_wrapper"
|
| 54 |
+
cachable = False
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
fs=None,
|
| 59 |
+
asynchronous=None,
|
| 60 |
+
target_protocol=None,
|
| 61 |
+
target_options=None,
|
| 62 |
+
semaphore=None,
|
| 63 |
+
max_concurrent_tasks=None,
|
| 64 |
+
**kwargs,
|
| 65 |
+
):
|
| 66 |
+
if asynchronous is None:
|
| 67 |
+
asynchronous = running_async()
|
| 68 |
+
super().__init__(asynchronous=asynchronous, **kwargs)
|
| 69 |
+
if fs is not None:
|
| 70 |
+
self.sync_fs = fs
|
| 71 |
+
else:
|
| 72 |
+
self.sync_fs = fsspec.filesystem(target_protocol, **target_options)
|
| 73 |
+
self.protocol = self.sync_fs.protocol
|
| 74 |
+
# paths must be normalized the way the wrapped filesystem does it
|
| 75 |
+
self.root_marker = self.sync_fs.root_marker
|
| 76 |
+
self._strip_protocol = self.sync_fs._strip_protocol
|
| 77 |
+
self._parent = self.sync_fs._parent
|
| 78 |
+
self.semaphore = semaphore
|
| 79 |
+
self._wrap_all_sync_methods()
|
| 80 |
+
|
| 81 |
+
@property
|
| 82 |
+
def fsid(self):
|
| 83 |
+
return f"async_{self.sync_fs.fsid}"
|
| 84 |
+
|
| 85 |
+
def _wrap_all_sync_methods(self):
|
| 86 |
+
"""
|
| 87 |
+
Wrap all synchronous methods of the underlying filesystem with asynchronous versions.
|
| 88 |
+
"""
|
| 89 |
+
excluded_methods = {"open"}
|
| 90 |
+
for method_name in dir(self.sync_fs):
|
| 91 |
+
if method_name.startswith("_") or method_name in excluded_methods:
|
| 92 |
+
continue
|
| 93 |
+
|
| 94 |
+
attr = inspect.getattr_static(self.sync_fs, method_name)
|
| 95 |
+
if isinstance(attr, property):
|
| 96 |
+
continue
|
| 97 |
+
|
| 98 |
+
method = getattr(self.sync_fs, method_name)
|
| 99 |
+
# generators such as ``walk`` cannot become coroutines: the async API
|
| 100 |
+
# expects async generators, which AsyncFileSystem already builds on
|
| 101 |
+
# top of the wrapped methods (``_walk`` uses ``_ls``)
|
| 102 |
+
if (
|
| 103 |
+
callable(method)
|
| 104 |
+
and not inspect.iscoroutinefunction(method)
|
| 105 |
+
and not inspect.isgeneratorfunction(method)
|
| 106 |
+
):
|
| 107 |
+
async_method = async_wrapper(method, obj=self, semaphore=self.semaphore)
|
| 108 |
+
setattr(self, f"_{method_name}", async_method)
|
| 109 |
+
|
| 110 |
+
@classmethod
|
| 111 |
+
def wrap_class(cls, sync_fs_class):
|
| 112 |
+
"""
|
| 113 |
+
Create a new class that can be used to instantiate an AsyncFileSystemWrapper
|
| 114 |
+
with lazy instantiation of the underlying synchronous filesystem.
|
| 115 |
+
|
| 116 |
+
Parameters
|
| 117 |
+
----------
|
| 118 |
+
sync_fs_class : type
|
| 119 |
+
The class of the synchronous filesystem to wrap.
|
| 120 |
+
|
| 121 |
+
Returns
|
| 122 |
+
-------
|
| 123 |
+
type
|
| 124 |
+
A new class that wraps the provided synchronous filesystem class.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
class GeneratedAsyncFileSystemWrapper(cls):
|
| 128 |
+
def __init__(self, *args, **kwargs):
|
| 129 |
+
sync_fs = sync_fs_class(*args, **kwargs)
|
| 130 |
+
super().__init__(sync_fs)
|
| 131 |
+
|
| 132 |
+
GeneratedAsyncFileSystemWrapper.__name__ = (
|
| 133 |
+
f"Async{sync_fs_class.__name__}Wrapper"
|
| 134 |
+
)
|
| 135 |
+
return GeneratedAsyncFileSystemWrapper
|
tasks/tasksmith-3bb3c78392c6/tests/source/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()
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cache_metadata.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/cached.py
ADDED
|
@@ -0,0 +1,1224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import inspect
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
import secrets
|
| 8 |
+
import tempfile
|
| 9 |
+
import time
|
| 10 |
+
import weakref
|
| 11 |
+
from collections.abc import Callable
|
| 12 |
+
from contextlib import ExitStack, contextmanager, suppress
|
| 13 |
+
from hashlib import sha256
|
| 14 |
+
from shutil import rmtree
|
| 15 |
+
from typing import TYPE_CHECKING, Any, ClassVar
|
| 16 |
+
|
| 17 |
+
from fsspec import filesystem
|
| 18 |
+
from fsspec.asyn import _run_coros_in_chunks
|
| 19 |
+
from fsspec.callbacks import DEFAULT_CALLBACK
|
| 20 |
+
from fsspec.compression import compr
|
| 21 |
+
from fsspec.core import BaseCache, MMapCache
|
| 22 |
+
from fsspec.exceptions import BlocksizeMismatchError
|
| 23 |
+
from fsspec.implementations.cache_mapper import create_cache_mapper
|
| 24 |
+
from fsspec.implementations.cache_metadata import CacheMetadata
|
| 25 |
+
from fsspec.implementations.chained import ChainedFileSystem
|
| 26 |
+
from fsspec.implementations.local import LocalFileSystem
|
| 27 |
+
from fsspec.spec import AbstractBufferedFile, AbstractFileSystem
|
| 28 |
+
from fsspec.transaction import Transaction
|
| 29 |
+
from fsspec.utils import infer_compression
|
| 30 |
+
|
| 31 |
+
if TYPE_CHECKING:
|
| 32 |
+
from fsspec.implementations.cache_mapper import AbstractCacheMapper
|
| 33 |
+
|
| 34 |
+
logger = logging.getLogger("fsspec.cached")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@contextmanager
|
| 38 |
+
def _tempfile(lpath):
|
| 39 |
+
# download to a temporary file, renamed into place once complete, so that
|
| 40 |
+
# a partial download is never visible under its final cache name (#639)
|
| 41 |
+
tmp = os.path.join(os.path.dirname(lpath), f"{secrets.token_hex(8)}.part")
|
| 42 |
+
try:
|
| 43 |
+
# stamp the start from the filesystem's clock: windows mtimes can lag time.time()
|
| 44 |
+
open(tmp, "wb").close()
|
| 45 |
+
start = os.path.getmtime(tmp)
|
| 46 |
+
os.remove(tmp)
|
| 47 |
+
yield tmp
|
| 48 |
+
try:
|
| 49 |
+
os.replace(tmp, lpath)
|
| 50 |
+
except PermissionError:
|
| 51 |
+
# windows: destination open elsewhere. A same-size file written
|
| 52 |
+
# since we started is a concurrent copy of the same download.
|
| 53 |
+
if not (
|
| 54 |
+
os.path.isfile(lpath)
|
| 55 |
+
and os.path.getsize(lpath) == os.path.getsize(tmp)
|
| 56 |
+
and os.path.getmtime(lpath) >= start
|
| 57 |
+
):
|
| 58 |
+
raise
|
| 59 |
+
finally:
|
| 60 |
+
with suppress(OSError):
|
| 61 |
+
os.remove(tmp)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _atomic_get(fs, rpaths, lpaths, callback=DEFAULT_CALLBACK):
|
| 65 |
+
with ExitStack() as stack:
|
| 66 |
+
fs.get(
|
| 67 |
+
rpaths,
|
| 68 |
+
[stack.enter_context(_tempfile(fn)) for fn in lpaths],
|
| 69 |
+
callback=callback,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class WriteCachedTransaction(Transaction):
|
| 74 |
+
def complete(self, commit=True):
|
| 75 |
+
if not commit:
|
| 76 |
+
return super().complete(commit=False)
|
| 77 |
+
rpaths = [f.path for f in self.files]
|
| 78 |
+
lpaths = [f.fn for f in self.files]
|
| 79 |
+
if commit:
|
| 80 |
+
self.fs.put(lpaths, rpaths)
|
| 81 |
+
self.files.clear()
|
| 82 |
+
self.fs._intrans = False
|
| 83 |
+
self.fs._transaction = None
|
| 84 |
+
self.fs = None # break cycle
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class CachingFileSystem(ChainedFileSystem):
|
| 88 |
+
"""Locally caching filesystem, layer over any other FS
|
| 89 |
+
|
| 90 |
+
This class implements chunk-wise local storage of remote files, for quick
|
| 91 |
+
access after the initial download. The files are stored in a given
|
| 92 |
+
directory with hashes of URLs for the filenames. If no directory is given,
|
| 93 |
+
a temporary one is used, which should be cleaned up by the OS after the
|
| 94 |
+
process ends. The files themselves are sparse (as implemented in
|
| 95 |
+
:class:`~fsspec.caching.MMapCache`), so only the data which is accessed
|
| 96 |
+
takes up space.
|
| 97 |
+
|
| 98 |
+
Restrictions:
|
| 99 |
+
|
| 100 |
+
- the block-size must be the same for each access of a given file, unless
|
| 101 |
+
all blocks of the file have already been read
|
| 102 |
+
- caching can only be applied to file-systems which produce files
|
| 103 |
+
derived from fsspec.spec.AbstractBufferedFile.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
protocol: ClassVar[str | tuple[str, ...]] = ("blockcache", "cached")
|
| 107 |
+
_strip_tokenize_options = ("fo",)
|
| 108 |
+
|
| 109 |
+
def __init__(
|
| 110 |
+
self,
|
| 111 |
+
target_protocol=None,
|
| 112 |
+
cache_storage="TMP",
|
| 113 |
+
cache_check=10,
|
| 114 |
+
check_files=False,
|
| 115 |
+
expiry_time=604800,
|
| 116 |
+
target_options=None,
|
| 117 |
+
fs=None,
|
| 118 |
+
same_names: bool | None = None,
|
| 119 |
+
compression=None,
|
| 120 |
+
cache_mapper: AbstractCacheMapper | None = None,
|
| 121 |
+
cache_storage_mode=None,
|
| 122 |
+
callback=DEFAULT_CALLBACK,
|
| 123 |
+
**kwargs,
|
| 124 |
+
):
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
Parameters
|
| 128 |
+
----------
|
| 129 |
+
target_protocol: str (optional)
|
| 130 |
+
Target filesystem protocol. Provide either this or ``fs``.
|
| 131 |
+
cache_storage: str or list(str)
|
| 132 |
+
Location to store files. If "TMP", this is a temporary directory,
|
| 133 |
+
and will be cleaned up by the OS when this process ends (or later).
|
| 134 |
+
If a list, each location will be tried in the order given, but
|
| 135 |
+
only the last will be considered writable.
|
| 136 |
+
cache_check: int
|
| 137 |
+
Number of seconds between reload of cache metadata
|
| 138 |
+
check_files: bool
|
| 139 |
+
Whether to explicitly see if the UID of the remote file matches
|
| 140 |
+
the stored one before using. Warning: some file systems such as
|
| 141 |
+
HTTP cannot reliably give a unique hash of the contents of some
|
| 142 |
+
path, so be sure to set this option to False.
|
| 143 |
+
expiry_time: int
|
| 144 |
+
The time in seconds after which a local copy is considered useless.
|
| 145 |
+
Set to falsy to prevent expiry. The default is equivalent to one
|
| 146 |
+
week.
|
| 147 |
+
target_options: dict or None
|
| 148 |
+
Passed to the instantiation of the FS, if fs is None.
|
| 149 |
+
fs: filesystem instance
|
| 150 |
+
The target filesystem to run against. Provide this or ``protocol``.
|
| 151 |
+
same_names: bool (optional)
|
| 152 |
+
By default, target URLs are hashed using a ``HashCacheMapper`` so
|
| 153 |
+
that files from different backends with the same basename do not
|
| 154 |
+
conflict. If this argument is ``true``, a ``BasenameCacheMapper``
|
| 155 |
+
is used instead. Other cache mapper options are available by using
|
| 156 |
+
the ``cache_mapper`` keyword argument. Only one of this and
|
| 157 |
+
``cache_mapper`` should be specified.
|
| 158 |
+
compression: str (optional)
|
| 159 |
+
To decompress on download. Can be 'infer' (guess from the URL name),
|
| 160 |
+
one of the entries in ``fsspec.compression.compr``, or None for no
|
| 161 |
+
decompression.
|
| 162 |
+
cache_mapper: AbstractCacheMapper (optional)
|
| 163 |
+
The object use to map from original filenames to cached filenames.
|
| 164 |
+
Only one of this and ``same_names`` should be specified.
|
| 165 |
+
cache_storage_mode: int (optional)
|
| 166 |
+
Permission mode used when creating the cache storage directory,
|
| 167 |
+
e.g. ``0o700``. The default of ``None`` leaves the directory at
|
| 168 |
+
the system default (governed by the umask), which is the existing
|
| 169 |
+
behaviour. Pass an octal mode such as ``0o700`` to keep the cache
|
| 170 |
+
directory, and so the cached data files within it, readable by the
|
| 171 |
+
owner only.
|
| 172 |
+
callback: fsspec.callbacks.Callback (optional)
|
| 173 |
+
Receives the progress of the downloads made into the cache on a
|
| 174 |
+
cache miss, i.e. the ``get`` operations on the target filesystem
|
| 175 |
+
when ``filecache`` or ``simplecache`` first open, ``cat`` or
|
| 176 |
+
``cat_ranges`` a file. The block-wise ``blockcache`` fetches
|
| 177 |
+
ranges on demand and does not use it.
|
| 178 |
+
"""
|
| 179 |
+
super().__init__(**kwargs)
|
| 180 |
+
if fs is None and target_protocol is None:
|
| 181 |
+
raise ValueError(
|
| 182 |
+
"Please provide filesystem instance(fs) or target_protocol"
|
| 183 |
+
)
|
| 184 |
+
if not (fs is None) ^ (target_protocol is None):
|
| 185 |
+
raise ValueError(
|
| 186 |
+
"Both filesystems (fs) and target_protocol may not be both given."
|
| 187 |
+
)
|
| 188 |
+
if cache_storage == "TMP":
|
| 189 |
+
tempdir = tempfile.mkdtemp()
|
| 190 |
+
storage = [tempdir]
|
| 191 |
+
weakref.finalize(self, self._remove_tempdir, tempdir)
|
| 192 |
+
else:
|
| 193 |
+
if isinstance(cache_storage, str):
|
| 194 |
+
storage = [cache_storage]
|
| 195 |
+
else:
|
| 196 |
+
storage = cache_storage
|
| 197 |
+
self.cache_storage_mode = cache_storage_mode
|
| 198 |
+
self._makedirs(storage[-1])
|
| 199 |
+
self.storage = storage
|
| 200 |
+
self.kwargs = target_options or {}
|
| 201 |
+
self.cache_check = cache_check
|
| 202 |
+
self.check_files = check_files
|
| 203 |
+
self.expiry = expiry_time
|
| 204 |
+
self.compression = compression
|
| 205 |
+
self.callback = callback
|
| 206 |
+
|
| 207 |
+
# Size of cache in bytes. If None then the size is unknown and will be
|
| 208 |
+
# recalculated the next time cache_size() is called. On writes to the
|
| 209 |
+
# cache this is reset to None.
|
| 210 |
+
self._cache_size = None
|
| 211 |
+
|
| 212 |
+
if same_names is not None and cache_mapper is not None:
|
| 213 |
+
raise ValueError(
|
| 214 |
+
"Cannot specify both same_names and cache_mapper in "
|
| 215 |
+
"CachingFileSystem.__init__"
|
| 216 |
+
)
|
| 217 |
+
if cache_mapper is not None:
|
| 218 |
+
self._mapper = cache_mapper
|
| 219 |
+
else:
|
| 220 |
+
self._mapper = create_cache_mapper(
|
| 221 |
+
same_names if same_names is not None else False
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
self.target_protocol = (
|
| 225 |
+
target_protocol
|
| 226 |
+
if isinstance(target_protocol, str)
|
| 227 |
+
else (fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0])
|
| 228 |
+
)
|
| 229 |
+
self._metadata = CacheMetadata(self.storage)
|
| 230 |
+
self.load_cache()
|
| 231 |
+
self.fs = fs if fs is not None else filesystem(target_protocol, **self.kwargs)
|
| 232 |
+
|
| 233 |
+
def _strip_protocol(path):
|
| 234 |
+
# acts as a method, since each instance has a difference target
|
| 235 |
+
return self.fs._strip_protocol(type(self)._strip_protocol(path))
|
| 236 |
+
|
| 237 |
+
self._strip_protocol: Callable = _strip_protocol
|
| 238 |
+
|
| 239 |
+
@staticmethod
|
| 240 |
+
def _remove_tempdir(tempdir):
|
| 241 |
+
try:
|
| 242 |
+
rmtree(tempdir)
|
| 243 |
+
except Exception:
|
| 244 |
+
pass
|
| 245 |
+
|
| 246 |
+
def _makedirs(self, path):
|
| 247 |
+
if self.cache_storage_mode is None:
|
| 248 |
+
os.makedirs(path, exist_ok=True)
|
| 249 |
+
else:
|
| 250 |
+
os.makedirs(path, exist_ok=True, mode=self.cache_storage_mode)
|
| 251 |
+
|
| 252 |
+
def _mkcache(self):
|
| 253 |
+
self._makedirs(self.storage[-1])
|
| 254 |
+
|
| 255 |
+
def cache_size(self):
|
| 256 |
+
"""Return size of cache in bytes.
|
| 257 |
+
|
| 258 |
+
If more than one cache directory is in use, only the size of the last
|
| 259 |
+
one (the writable cache directory) is returned.
|
| 260 |
+
"""
|
| 261 |
+
if self._cache_size is None:
|
| 262 |
+
cache_dir = self.storage[-1]
|
| 263 |
+
self._cache_size = filesystem("file").du(cache_dir, withdirs=True)
|
| 264 |
+
return self._cache_size
|
| 265 |
+
|
| 266 |
+
def load_cache(self):
|
| 267 |
+
"""Read set of stored blocks from file"""
|
| 268 |
+
self._metadata.load()
|
| 269 |
+
self._mkcache()
|
| 270 |
+
self.last_cache = time.time()
|
| 271 |
+
|
| 272 |
+
def save_cache(self):
|
| 273 |
+
"""Save set of stored blocks from file"""
|
| 274 |
+
self._mkcache()
|
| 275 |
+
self._metadata.save()
|
| 276 |
+
self.last_cache = time.time()
|
| 277 |
+
self._cache_size = None
|
| 278 |
+
|
| 279 |
+
def _check_cache(self):
|
| 280 |
+
"""Reload caches if time elapsed or any disappeared"""
|
| 281 |
+
self._mkcache()
|
| 282 |
+
if not self.cache_check:
|
| 283 |
+
# explicitly told not to bother checking
|
| 284 |
+
return
|
| 285 |
+
timecond = time.time() - self.last_cache > self.cache_check
|
| 286 |
+
existcond = all(os.path.exists(storage) for storage in self.storage)
|
| 287 |
+
if timecond or not existcond:
|
| 288 |
+
self.load_cache()
|
| 289 |
+
|
| 290 |
+
def _check_file(self, path):
|
| 291 |
+
"""Is path in cache and still valid"""
|
| 292 |
+
path = self._strip_protocol(path)
|
| 293 |
+
self._check_cache()
|
| 294 |
+
return self._metadata.check_file(path, self)
|
| 295 |
+
|
| 296 |
+
def clear_cache(self):
|
| 297 |
+
"""Remove all files and metadata from the cache
|
| 298 |
+
|
| 299 |
+
In the case of multiple cache locations, this clears only the last one,
|
| 300 |
+
which is assumed to be the read/write one.
|
| 301 |
+
"""
|
| 302 |
+
rmtree(self.storage[-1])
|
| 303 |
+
self.load_cache()
|
| 304 |
+
self._cache_size = None
|
| 305 |
+
|
| 306 |
+
def clear_expired_cache(self, expiry_time=None):
|
| 307 |
+
"""Remove all expired files and metadata from the cache
|
| 308 |
+
|
| 309 |
+
In the case of multiple cache locations, this clears only the last one,
|
| 310 |
+
which is assumed to be the read/write one.
|
| 311 |
+
|
| 312 |
+
Parameters
|
| 313 |
+
----------
|
| 314 |
+
expiry_time: int
|
| 315 |
+
The time in seconds after which a local copy is considered useless.
|
| 316 |
+
If not defined the default is equivalent to the attribute from the
|
| 317 |
+
file caching instantiation.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
if expiry_time is None:
|
| 321 |
+
if not self.expiry:
|
| 322 |
+
# "Set to falsy to prevent expiry" (see __init__): nothing
|
| 323 |
+
# ever goes stale, so there is nothing to clear.
|
| 324 |
+
return
|
| 325 |
+
expiry_time = self.expiry
|
| 326 |
+
|
| 327 |
+
self._check_cache()
|
| 328 |
+
|
| 329 |
+
expired_files, writable_cache_empty = self._metadata.clear_expired(expiry_time)
|
| 330 |
+
for fn in expired_files:
|
| 331 |
+
if os.path.exists(fn):
|
| 332 |
+
os.remove(fn)
|
| 333 |
+
|
| 334 |
+
if writable_cache_empty:
|
| 335 |
+
rmtree(self.storage[-1])
|
| 336 |
+
self.load_cache()
|
| 337 |
+
|
| 338 |
+
self._cache_size = None
|
| 339 |
+
|
| 340 |
+
def pop_from_cache(self, path):
|
| 341 |
+
"""Remove cached version of given file
|
| 342 |
+
|
| 343 |
+
Deletes local copy of the given (remote) path. If it is found in a cache
|
| 344 |
+
location which is not the last, it is assumed to be read-only, and
|
| 345 |
+
raises PermissionError
|
| 346 |
+
"""
|
| 347 |
+
path = self._strip_protocol(path)
|
| 348 |
+
fn = self._metadata.pop_file(path)
|
| 349 |
+
if fn is not None:
|
| 350 |
+
os.remove(fn)
|
| 351 |
+
self._cache_size = None
|
| 352 |
+
|
| 353 |
+
def _open(
|
| 354 |
+
self,
|
| 355 |
+
path,
|
| 356 |
+
mode="rb",
|
| 357 |
+
block_size=None,
|
| 358 |
+
autocommit=True,
|
| 359 |
+
cache_options=None,
|
| 360 |
+
**kwargs,
|
| 361 |
+
):
|
| 362 |
+
"""Wrap the target _open
|
| 363 |
+
|
| 364 |
+
If the whole file exists in the cache, just open it locally and
|
| 365 |
+
return that.
|
| 366 |
+
|
| 367 |
+
Otherwise, open the file on the target FS, and make it have a mmap
|
| 368 |
+
cache pointing to the location which we determine, in our cache.
|
| 369 |
+
The ``blocks`` instance is shared, so as the mmap cache instance
|
| 370 |
+
updates, so does the entry in our ``cached_files`` attribute.
|
| 371 |
+
We monkey-patch this file, so that when it closes, we call
|
| 372 |
+
``close_and_update`` to save the state of the blocks.
|
| 373 |
+
"""
|
| 374 |
+
path = self._strip_protocol(path)
|
| 375 |
+
|
| 376 |
+
path = self.fs._strip_protocol(path)
|
| 377 |
+
if "r" not in mode:
|
| 378 |
+
return self.fs._open(
|
| 379 |
+
path,
|
| 380 |
+
mode=mode,
|
| 381 |
+
block_size=block_size,
|
| 382 |
+
autocommit=autocommit,
|
| 383 |
+
cache_options=cache_options,
|
| 384 |
+
**kwargs,
|
| 385 |
+
)
|
| 386 |
+
detail = self._check_file(path)
|
| 387 |
+
if detail:
|
| 388 |
+
# file is in cache
|
| 389 |
+
detail, fn = detail
|
| 390 |
+
hash, blocks = detail["fn"], detail["blocks"]
|
| 391 |
+
if blocks is True:
|
| 392 |
+
# stored file is complete
|
| 393 |
+
logger.debug("Opening local copy of %s", path)
|
| 394 |
+
return open(fn, mode)
|
| 395 |
+
# TODO: action where partial file exists in read-only cache
|
| 396 |
+
logger.debug("Opening partially cached copy of %s", path)
|
| 397 |
+
else:
|
| 398 |
+
hash = self._mapper(path)
|
| 399 |
+
fn = os.path.join(self.storage[-1], hash)
|
| 400 |
+
blocks = set()
|
| 401 |
+
detail = {
|
| 402 |
+
"original": path,
|
| 403 |
+
"fn": hash,
|
| 404 |
+
"blocks": blocks,
|
| 405 |
+
"time": time.time(),
|
| 406 |
+
"uid": self.fs.ukey(path),
|
| 407 |
+
}
|
| 408 |
+
self._metadata.update_file(path, detail)
|
| 409 |
+
logger.debug("Creating local sparse file for %s", path)
|
| 410 |
+
|
| 411 |
+
# explicitly submitting the size to the open call will avoid extra
|
| 412 |
+
# operations when opening. This is particularly relevant
|
| 413 |
+
# for any file that is read over a network, e.g. S3.
|
| 414 |
+
size = detail.get("size")
|
| 415 |
+
|
| 416 |
+
# call target filesystems open
|
| 417 |
+
self._mkcache()
|
| 418 |
+
f = self.fs._open(
|
| 419 |
+
path,
|
| 420 |
+
mode=mode,
|
| 421 |
+
block_size=block_size,
|
| 422 |
+
autocommit=autocommit,
|
| 423 |
+
cache_options=cache_options,
|
| 424 |
+
cache_type="none",
|
| 425 |
+
size=size,
|
| 426 |
+
**kwargs,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
# set size if not already set
|
| 430 |
+
if size is None:
|
| 431 |
+
detail["size"] = f.size
|
| 432 |
+
self._metadata.update_file(path, detail)
|
| 433 |
+
|
| 434 |
+
if self.compression:
|
| 435 |
+
comp = (
|
| 436 |
+
infer_compression(path)
|
| 437 |
+
if self.compression == "infer"
|
| 438 |
+
else self.compression
|
| 439 |
+
)
|
| 440 |
+
f = compr[comp](f, mode="rb")
|
| 441 |
+
if "blocksize" in detail:
|
| 442 |
+
if detail["blocksize"] != f.blocksize:
|
| 443 |
+
raise BlocksizeMismatchError(
|
| 444 |
+
f"Cached file must be reopened with same block"
|
| 445 |
+
f" size as original (old: {detail['blocksize']},"
|
| 446 |
+
f" new {f.blocksize})"
|
| 447 |
+
)
|
| 448 |
+
else:
|
| 449 |
+
detail["blocksize"] = f.blocksize
|
| 450 |
+
|
| 451 |
+
def _fetch_ranges(ranges):
|
| 452 |
+
return self.fs.cat_ranges(
|
| 453 |
+
[path] * len(ranges),
|
| 454 |
+
[r[0] for r in ranges],
|
| 455 |
+
[r[1] for r in ranges],
|
| 456 |
+
**kwargs,
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
multi_fetcher = None if self.compression else _fetch_ranges
|
| 460 |
+
f.cache = MMapCache(
|
| 461 |
+
f.blocksize, f._fetch_range, f.size, fn, blocks, multi_fetcher=multi_fetcher
|
| 462 |
+
)
|
| 463 |
+
close = f.close
|
| 464 |
+
f.close = lambda: self.close_and_update(f, close)
|
| 465 |
+
self.save_cache()
|
| 466 |
+
return f
|
| 467 |
+
|
| 468 |
+
def _parent(self, path):
|
| 469 |
+
return self.fs._parent(path)
|
| 470 |
+
|
| 471 |
+
def hash_name(self, path: str, *args: Any) -> str:
|
| 472 |
+
# Kept for backward compatibility with downstream libraries.
|
| 473 |
+
# Ignores extra arguments, previously same_name boolean.
|
| 474 |
+
return self._mapper(path)
|
| 475 |
+
|
| 476 |
+
def close_and_update(self, f, close):
|
| 477 |
+
"""Called when a file is closing, so store the set of blocks"""
|
| 478 |
+
if f.closed:
|
| 479 |
+
return
|
| 480 |
+
path = self._strip_protocol(f.path)
|
| 481 |
+
self._metadata.on_close_cached_file(f, path)
|
| 482 |
+
try:
|
| 483 |
+
logger.debug("going to save")
|
| 484 |
+
self.save_cache()
|
| 485 |
+
logger.debug("saved")
|
| 486 |
+
except OSError:
|
| 487 |
+
logger.debug("Cache saving failed while closing file")
|
| 488 |
+
except NameError:
|
| 489 |
+
logger.debug("Cache save failed due to interpreter shutdown")
|
| 490 |
+
close()
|
| 491 |
+
f.closed = True
|
| 492 |
+
|
| 493 |
+
def ls(self, path, detail=True, **kwargs):
|
| 494 |
+
return self.fs.ls(path, detail, **kwargs)
|
| 495 |
+
|
| 496 |
+
def __getattribute__(self, item):
|
| 497 |
+
if item in {
|
| 498 |
+
"load_cache",
|
| 499 |
+
"_get_cached_file_before_open",
|
| 500 |
+
"_open",
|
| 501 |
+
"save_cache",
|
| 502 |
+
"close_and_update",
|
| 503 |
+
"__init__",
|
| 504 |
+
"__getattribute__",
|
| 505 |
+
"__reduce__",
|
| 506 |
+
"_make_local_details",
|
| 507 |
+
"_ukey_async",
|
| 508 |
+
"_check_file_async",
|
| 509 |
+
"_download_async",
|
| 510 |
+
"open",
|
| 511 |
+
"cat",
|
| 512 |
+
"cat_file",
|
| 513 |
+
"_cat_file",
|
| 514 |
+
"cat_ranges",
|
| 515 |
+
"_cat_ranges",
|
| 516 |
+
"_local_paths_for_ranges",
|
| 517 |
+
"get",
|
| 518 |
+
"read_block",
|
| 519 |
+
"tail",
|
| 520 |
+
"head",
|
| 521 |
+
"info",
|
| 522 |
+
"ls",
|
| 523 |
+
"exists",
|
| 524 |
+
"isfile",
|
| 525 |
+
"isdir",
|
| 526 |
+
"_check_file",
|
| 527 |
+
"_check_cache",
|
| 528 |
+
"_makedirs",
|
| 529 |
+
"_mkcache",
|
| 530 |
+
"clear_cache",
|
| 531 |
+
"clear_expired_cache",
|
| 532 |
+
"pop_from_cache",
|
| 533 |
+
"local_file",
|
| 534 |
+
"_paths_from_path",
|
| 535 |
+
"get_mapper",
|
| 536 |
+
"open_many",
|
| 537 |
+
"commit_many",
|
| 538 |
+
"hash_name",
|
| 539 |
+
"__hash__",
|
| 540 |
+
"__eq__",
|
| 541 |
+
"to_json",
|
| 542 |
+
"to_dict",
|
| 543 |
+
"cache_size",
|
| 544 |
+
"pipe_file",
|
| 545 |
+
"pipe",
|
| 546 |
+
"start_transaction",
|
| 547 |
+
"end_transaction",
|
| 548 |
+
}:
|
| 549 |
+
# all the methods defined in this class. Note `open` here, since
|
| 550 |
+
# it calls `_open`, but is actually in superclass
|
| 551 |
+
if hasattr(type(self), item):
|
| 552 |
+
return lambda *args, **kw: getattr(type(self), item).__get__(self)(
|
| 553 |
+
*args, **kw
|
| 554 |
+
)
|
| 555 |
+
# method is in the whitelist but not defined on this subclass;
|
| 556 |
+
# fall through to delegate to the wrapped filesystem below
|
| 557 |
+
if item in ["__reduce_ex__"]:
|
| 558 |
+
raise AttributeError
|
| 559 |
+
if item in ["transaction"]:
|
| 560 |
+
# property
|
| 561 |
+
return type(self).transaction.__get__(self)
|
| 562 |
+
if item in {"_cache", "transaction_type", "protocol"}:
|
| 563 |
+
# class attributes
|
| 564 |
+
return getattr(type(self), item)
|
| 565 |
+
if item == "__class__":
|
| 566 |
+
return type(self)
|
| 567 |
+
d = object.__getattribute__(self, "__dict__")
|
| 568 |
+
fs = d.get("fs", None) # fs is not immediately defined
|
| 569 |
+
if item in d:
|
| 570 |
+
return d[item]
|
| 571 |
+
elif fs is not None:
|
| 572 |
+
if item in fs.__dict__:
|
| 573 |
+
# attribute of instance
|
| 574 |
+
return fs.__dict__[item]
|
| 575 |
+
# attributed belonging to the target filesystem
|
| 576 |
+
cls = type(fs)
|
| 577 |
+
m = getattr(cls, item)
|
| 578 |
+
if (inspect.isfunction(m) or inspect.isdatadescriptor(m)) and (
|
| 579 |
+
not hasattr(m, "__self__") or m.__self__ is None
|
| 580 |
+
):
|
| 581 |
+
# instance method
|
| 582 |
+
return m.__get__(fs, cls)
|
| 583 |
+
return m # class method or attribute
|
| 584 |
+
else:
|
| 585 |
+
# attributes of the superclass, while target is being set up
|
| 586 |
+
return super().__getattribute__(item)
|
| 587 |
+
|
| 588 |
+
def __eq__(self, other):
|
| 589 |
+
"""Test for equality."""
|
| 590 |
+
if self is other:
|
| 591 |
+
return True
|
| 592 |
+
if not isinstance(other, type(self)):
|
| 593 |
+
return False
|
| 594 |
+
return (
|
| 595 |
+
self.storage == other.storage
|
| 596 |
+
and self.kwargs == other.kwargs
|
| 597 |
+
and self.cache_check == other.cache_check
|
| 598 |
+
and self.check_files == other.check_files
|
| 599 |
+
and self.expiry == other.expiry
|
| 600 |
+
and self.compression == other.compression
|
| 601 |
+
and self._mapper == other._mapper
|
| 602 |
+
and self.target_protocol == other.target_protocol
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
def __hash__(self):
|
| 606 |
+
"""Calculate hash."""
|
| 607 |
+
return (
|
| 608 |
+
hash(tuple(self.storage))
|
| 609 |
+
^ hash(str(self.kwargs))
|
| 610 |
+
^ hash(self.cache_check)
|
| 611 |
+
^ hash(self.check_files)
|
| 612 |
+
^ hash(self.expiry)
|
| 613 |
+
^ hash(self.compression)
|
| 614 |
+
^ hash(self._mapper)
|
| 615 |
+
^ hash(self.target_protocol)
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class WholeFileCacheFileSystem(CachingFileSystem):
|
| 620 |
+
"""Caches whole remote files on first access
|
| 621 |
+
|
| 622 |
+
This class is intended as a layer over any other file system, and
|
| 623 |
+
will make a local copy of each file accessed, so that all subsequent
|
| 624 |
+
reads are local. This is similar to ``CachingFileSystem``, but without
|
| 625 |
+
the block-wise functionality and so can work even when sparse files
|
| 626 |
+
are not allowed. See its docstring for definition of the init
|
| 627 |
+
arguments.
|
| 628 |
+
|
| 629 |
+
The class still needs access to the remote store for listing files,
|
| 630 |
+
and may refresh cached files.
|
| 631 |
+
"""
|
| 632 |
+
|
| 633 |
+
protocol = "filecache"
|
| 634 |
+
local_file = True
|
| 635 |
+
|
| 636 |
+
def open_many(self, open_files, **kwargs):
|
| 637 |
+
paths = [of.path for of in open_files]
|
| 638 |
+
if "r" in open_files.mode:
|
| 639 |
+
self._mkcache()
|
| 640 |
+
else:
|
| 641 |
+
return [
|
| 642 |
+
LocalTempFile(
|
| 643 |
+
self.fs,
|
| 644 |
+
path,
|
| 645 |
+
mode=open_files.mode,
|
| 646 |
+
fn=os.path.join(self.storage[-1], self._mapper(path)),
|
| 647 |
+
**kwargs,
|
| 648 |
+
)
|
| 649 |
+
for path in paths
|
| 650 |
+
]
|
| 651 |
+
|
| 652 |
+
if self.compression:
|
| 653 |
+
raise NotImplementedError
|
| 654 |
+
details = [self._check_file(sp) for sp in paths]
|
| 655 |
+
downpath = [p for p, d in zip(paths, details) if not d]
|
| 656 |
+
downfn0 = [
|
| 657 |
+
os.path.join(self.storage[-1], self._mapper(p))
|
| 658 |
+
for p, d in zip(paths, details)
|
| 659 |
+
] # keep these path names for opening later
|
| 660 |
+
downfn = [fn for fn, d in zip(downfn0, details) if not d]
|
| 661 |
+
if downpath:
|
| 662 |
+
# skip if all files are already cached and up to date
|
| 663 |
+
_atomic_get(self.fs, downpath, downfn, callback=self.callback)
|
| 664 |
+
|
| 665 |
+
# update metadata - only happens when downloads are successful
|
| 666 |
+
newdetail = [
|
| 667 |
+
{
|
| 668 |
+
"original": path,
|
| 669 |
+
"fn": self._mapper(path),
|
| 670 |
+
"blocks": True,
|
| 671 |
+
"time": time.time(),
|
| 672 |
+
"uid": self.fs.ukey(path),
|
| 673 |
+
}
|
| 674 |
+
for path in downpath
|
| 675 |
+
]
|
| 676 |
+
for path, detail in zip(downpath, newdetail):
|
| 677 |
+
self._metadata.update_file(path, detail)
|
| 678 |
+
self.save_cache()
|
| 679 |
+
|
| 680 |
+
def firstpart(fn):
|
| 681 |
+
# helper to adapt both whole-file and simple-cache
|
| 682 |
+
return fn[1] if isinstance(fn, tuple) else fn
|
| 683 |
+
|
| 684 |
+
return [
|
| 685 |
+
open(firstpart(fn0) if fn0 else fn1, mode=open_files.mode)
|
| 686 |
+
for fn0, fn1 in zip(details, downfn0)
|
| 687 |
+
]
|
| 688 |
+
|
| 689 |
+
def commit_many(self, open_files):
|
| 690 |
+
self.fs.put([f.fn for f in open_files], [f.path for f in open_files])
|
| 691 |
+
[f.close() for f in open_files]
|
| 692 |
+
for f in open_files:
|
| 693 |
+
# in case autocommit is off, and so close did not already delete
|
| 694 |
+
try:
|
| 695 |
+
os.remove(f.name)
|
| 696 |
+
except FileNotFoundError:
|
| 697 |
+
pass
|
| 698 |
+
self._cache_size = None
|
| 699 |
+
|
| 700 |
+
def _make_local_details(self, path, uid=None):
|
| 701 |
+
hash = self._mapper(path)
|
| 702 |
+
fn = os.path.join(self.storage[-1], hash)
|
| 703 |
+
detail = {
|
| 704 |
+
"original": path,
|
| 705 |
+
"fn": hash,
|
| 706 |
+
"blocks": True,
|
| 707 |
+
"time": time.time(),
|
| 708 |
+
"uid": self.fs.ukey(path) if uid is None else uid,
|
| 709 |
+
}
|
| 710 |
+
self._metadata.update_file(path, detail)
|
| 711 |
+
logger.debug("Copying %s to local cache", path)
|
| 712 |
+
return fn
|
| 713 |
+
|
| 714 |
+
async def _ukey_async(self, path):
|
| 715 |
+
# the default ukey calls sync info(), which fails in a running loop;
|
| 716 |
+
# an override may too (s3fs's does), so run it off the loop
|
| 717 |
+
if type(self.fs).ukey is AbstractFileSystem.ukey:
|
| 718 |
+
return sha256(str(await self.fs._info(path)).encode()).hexdigest()
|
| 719 |
+
return await asyncio.to_thread(self.fs.ukey, path)
|
| 720 |
+
|
| 721 |
+
async def _check_file_async(self, path):
|
| 722 |
+
# _check_file, with the async-safe ukey for check_files
|
| 723 |
+
self._check_cache()
|
| 724 |
+
detail = self._metadata.check_file(path, None)
|
| 725 |
+
if not detail:
|
| 726 |
+
return False
|
| 727 |
+
detail, fn = detail
|
| 728 |
+
if self.check_files and detail["uid"] != await self._ukey_async(path):
|
| 729 |
+
return False
|
| 730 |
+
if self.expiry and time.time() - detail["time"] > self.expiry:
|
| 731 |
+
return False
|
| 732 |
+
if detail["blocks"] is not True:
|
| 733 |
+
return False # a partial blockcache entry sharing this directory
|
| 734 |
+
return fn
|
| 735 |
+
|
| 736 |
+
async def _download_async(self, path, fn, **kwargs):
|
| 737 |
+
kwargs.setdefault("callback", self.callback)
|
| 738 |
+
with _tempfile(fn) as tmp:
|
| 739 |
+
await self.fs._get_file(path, tmp, **kwargs)
|
| 740 |
+
if not self.compression:
|
| 741 |
+
# a compressed download is left unrecorded, for open() to redo
|
| 742 |
+
self._make_local_details(path, uid=await self._ukey_async(path))
|
| 743 |
+
|
| 744 |
+
def cat(
|
| 745 |
+
self,
|
| 746 |
+
path,
|
| 747 |
+
recursive=False,
|
| 748 |
+
on_error="raise",
|
| 749 |
+
callback=DEFAULT_CALLBACK,
|
| 750 |
+
**kwargs,
|
| 751 |
+
):
|
| 752 |
+
paths = self.expand_path(
|
| 753 |
+
path, recursive=recursive, maxdepth=kwargs.get("maxdepth")
|
| 754 |
+
)
|
| 755 |
+
getpaths = []
|
| 756 |
+
storepaths = []
|
| 757 |
+
fns = []
|
| 758 |
+
out = {}
|
| 759 |
+
for p in paths.copy():
|
| 760 |
+
try:
|
| 761 |
+
detail = self._check_file(p)
|
| 762 |
+
if not detail:
|
| 763 |
+
if self.compression:
|
| 764 |
+
self._get_cached_file_before_open(p)
|
| 765 |
+
fn = os.path.join(self.storage[-1], self._mapper(p))
|
| 766 |
+
else:
|
| 767 |
+
fn = self._make_local_details(p)
|
| 768 |
+
getpaths.append(p)
|
| 769 |
+
storepaths.append(fn)
|
| 770 |
+
else:
|
| 771 |
+
detail, fn = detail if isinstance(detail, tuple) else (None, detail)
|
| 772 |
+
fns.append(fn)
|
| 773 |
+
except Exception as e:
|
| 774 |
+
if on_error == "raise":
|
| 775 |
+
raise
|
| 776 |
+
if on_error == "return":
|
| 777 |
+
out[p] = e
|
| 778 |
+
paths.remove(p)
|
| 779 |
+
|
| 780 |
+
if getpaths:
|
| 781 |
+
_atomic_get(self.fs, getpaths, storepaths, callback=self.callback)
|
| 782 |
+
self.save_cache()
|
| 783 |
+
|
| 784 |
+
callback.set_size(len(paths))
|
| 785 |
+
for p, fn in zip(paths, fns):
|
| 786 |
+
with open(fn, "rb") as f:
|
| 787 |
+
out[p] = f.read()
|
| 788 |
+
callback.relative_update(1)
|
| 789 |
+
if isinstance(path, str) and len(paths) == 1 and recursive is False:
|
| 790 |
+
out = out[paths[0]]
|
| 791 |
+
return out
|
| 792 |
+
|
| 793 |
+
def _get_cached_file_before_open(self, path, **kwargs):
|
| 794 |
+
fn = self._make_local_details(path)
|
| 795 |
+
# call target filesystems open
|
| 796 |
+
self._mkcache()
|
| 797 |
+
if self.compression:
|
| 798 |
+
with (
|
| 799 |
+
_tempfile(fn) as tmp,
|
| 800 |
+
self.fs._open(path, mode="rb", **kwargs) as f,
|
| 801 |
+
open(tmp, "wb") as f2,
|
| 802 |
+
):
|
| 803 |
+
if isinstance(f, AbstractBufferedFile):
|
| 804 |
+
# want no type of caching if just downloading whole thing
|
| 805 |
+
f.cache = BaseCache(0, f.cache.fetcher, f.size)
|
| 806 |
+
comp = (
|
| 807 |
+
infer_compression(path)
|
| 808 |
+
if self.compression == "infer"
|
| 809 |
+
else self.compression
|
| 810 |
+
)
|
| 811 |
+
f = compr[comp](f, mode="rb")
|
| 812 |
+
data = True
|
| 813 |
+
while data:
|
| 814 |
+
block = getattr(f, "blocksize", 5 * 2**20)
|
| 815 |
+
data = f.read(block)
|
| 816 |
+
f2.write(data)
|
| 817 |
+
else:
|
| 818 |
+
with _tempfile(fn) as tmp:
|
| 819 |
+
self.fs.get_file(path, tmp, callback=self.callback)
|
| 820 |
+
self.save_cache()
|
| 821 |
+
return self._metadata.cached_files[-1][path].copy(), fn
|
| 822 |
+
|
| 823 |
+
def _open(self, path, mode="rb", **kwargs):
|
| 824 |
+
path = self._strip_protocol(path)
|
| 825 |
+
# For read (or append), (try) download from remote
|
| 826 |
+
if "r" in mode or "a" in mode:
|
| 827 |
+
cached = self._check_file(path)
|
| 828 |
+
if not cached:
|
| 829 |
+
if self.fs.exists(path):
|
| 830 |
+
cached = self._get_cached_file_before_open(path, **kwargs)
|
| 831 |
+
elif "r" in mode:
|
| 832 |
+
raise FileNotFoundError(path)
|
| 833 |
+
|
| 834 |
+
# Use this open's selected file, even if it expired during download.
|
| 835 |
+
if cached:
|
| 836 |
+
detail, fn = cached
|
| 837 |
+
_, blocks = detail["fn"], detail["blocks"]
|
| 838 |
+
if blocks is True:
|
| 839 |
+
logger.debug("Opening local copy of %s", path)
|
| 840 |
+
else:
|
| 841 |
+
raise ValueError(
|
| 842 |
+
f"Attempt to open partially cached file {path}"
|
| 843 |
+
f" as a wholly cached file"
|
| 844 |
+
)
|
| 845 |
+
|
| 846 |
+
# Just reading does not need special file handling
|
| 847 |
+
if "r" in mode and "+" not in mode:
|
| 848 |
+
# In order to support downstream filesystems to be able to
|
| 849 |
+
# infer the compression from the original filename, like
|
| 850 |
+
# the `TarFileSystem`, let's extend the `io.BufferedReader`
|
| 851 |
+
# fileobject protocol by adding a dedicated attribute
|
| 852 |
+
# `original`.
|
| 853 |
+
f = open(fn, mode)
|
| 854 |
+
f.original = detail.get("original")
|
| 855 |
+
return f
|
| 856 |
+
|
| 857 |
+
hash = self._mapper(path)
|
| 858 |
+
fn = os.path.join(self.storage[-1], hash)
|
| 859 |
+
user_specified_kwargs = {
|
| 860 |
+
k: v
|
| 861 |
+
for k, v in kwargs.items()
|
| 862 |
+
# those kwargs were added by open(), we don't want them
|
| 863 |
+
if k not in ["autocommit", "block_size", "cache_options"]
|
| 864 |
+
}
|
| 865 |
+
return LocalTempFile(self, path, mode=mode, fn=fn, **user_specified_kwargs)
|
| 866 |
+
|
| 867 |
+
async def _cat_file(self, path, start=None, end=None, **kwargs):
|
| 868 |
+
logger.debug("async cat_file %s", path)
|
| 869 |
+
path = self._strip_protocol(path)
|
| 870 |
+
sha = self._mapper(path)
|
| 871 |
+
fn = await self._check_file_async(path)
|
| 872 |
+
|
| 873 |
+
if not fn:
|
| 874 |
+
fn = os.path.join(self.storage[-1], sha)
|
| 875 |
+
await self._download_async(path, fn, **kwargs)
|
| 876 |
+
self.save_cache()
|
| 877 |
+
|
| 878 |
+
with open(fn, "rb") as f: # noqa ASYNC230
|
| 879 |
+
if start:
|
| 880 |
+
f.seek(start)
|
| 881 |
+
size = -1 if end is None else end - f.tell()
|
| 882 |
+
return f.read(size)
|
| 883 |
+
|
| 884 |
+
def _local_paths_for_ranges(self, paths):
|
| 885 |
+
"""Cache file for each of paths, and which remote files to download
|
| 886 |
+
|
| 887 |
+
A path given more than once is downloaded once, and every occurrence
|
| 888 |
+
reads from the same cache file.
|
| 889 |
+
"""
|
| 890 |
+
lpaths = []
|
| 891 |
+
local = {}
|
| 892 |
+
download = []
|
| 893 |
+
rpaths = []
|
| 894 |
+
for p in paths:
|
| 895 |
+
if p not in local:
|
| 896 |
+
detail = self._check_file(p)
|
| 897 |
+
if not detail:
|
| 898 |
+
fn = os.path.join(self.storage[-1], self._mapper(p))
|
| 899 |
+
download.append(fn)
|
| 900 |
+
rpaths.append(p)
|
| 901 |
+
else:
|
| 902 |
+
# filecache returns (detail, fn), simplecache just fn
|
| 903 |
+
fn = detail[1] if isinstance(detail, tuple) else detail
|
| 904 |
+
local[p] = fn
|
| 905 |
+
lpaths.append(local[p])
|
| 906 |
+
return lpaths, rpaths, download
|
| 907 |
+
|
| 908 |
+
async def _cat_ranges(
|
| 909 |
+
self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
|
| 910 |
+
):
|
| 911 |
+
logger.debug("async cat ranges %s", paths)
|
| 912 |
+
# _local_paths_for_ranges, but the validity check is a coroutine here
|
| 913 |
+
paths = [self._strip_protocol(p) for p in paths]
|
| 914 |
+
lpaths = []
|
| 915 |
+
local = {}
|
| 916 |
+
need = {}
|
| 917 |
+
for p in paths:
|
| 918 |
+
if p not in local:
|
| 919 |
+
local[p] = await self._check_file_async(p) or need.setdefault(
|
| 920 |
+
p, os.path.join(self.storage[-1], self._mapper(p))
|
| 921 |
+
)
|
| 922 |
+
lpaths.append(local[p])
|
| 923 |
+
errors = {}
|
| 924 |
+
if need:
|
| 925 |
+
# not self.fs._get: each download needs its own temp file
|
| 926 |
+
results = await _run_coros_in_chunks(
|
| 927 |
+
[self._download_async(p, fn, **kwargs) for p, fn in need.items()],
|
| 928 |
+
batch_size=self.fs.batch_size,
|
| 929 |
+
return_exceptions=True,
|
| 930 |
+
)
|
| 931 |
+
errors = {p: e for p, e in zip(need, results) if isinstance(e, Exception)}
|
| 932 |
+
self.save_cache()
|
| 933 |
+
if errors and on_error == "raise":
|
| 934 |
+
raise next(iter(errors.values()))
|
| 935 |
+
|
| 936 |
+
out = LocalFileSystem().cat_ranges(
|
| 937 |
+
lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
|
| 938 |
+
)
|
| 939 |
+
if on_error == "return":
|
| 940 |
+
# report the download error, not the missing local copy
|
| 941 |
+
out = [errors.get(p, o) for p, o in zip(paths, out)]
|
| 942 |
+
return out
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
class SimpleCacheFileSystem(WholeFileCacheFileSystem):
|
| 946 |
+
"""Caches whole remote files on first access
|
| 947 |
+
|
| 948 |
+
This class is intended as a layer over any other file system, and
|
| 949 |
+
will make a local copy of each file accessed, so that all subsequent
|
| 950 |
+
reads are local. This implementation only copies whole files, and
|
| 951 |
+
does not keep any metadata about the download time or file details.
|
| 952 |
+
It is therefore safer to use in multi-threaded/concurrent situations.
|
| 953 |
+
|
| 954 |
+
This is the only of the caching filesystems that supports write: you will
|
| 955 |
+
be given a real local open file, and upon close and commit, it will be
|
| 956 |
+
uploaded to the target filesystem; the writability or the target URL is
|
| 957 |
+
not checked until that time.
|
| 958 |
+
|
| 959 |
+
"""
|
| 960 |
+
|
| 961 |
+
protocol = "simplecache"
|
| 962 |
+
local_file = True
|
| 963 |
+
transaction_type = WriteCachedTransaction
|
| 964 |
+
|
| 965 |
+
def __init__(self, **kwargs):
|
| 966 |
+
kw = kwargs.copy()
|
| 967 |
+
for key in ["cache_check", "expiry_time", "check_files"]:
|
| 968 |
+
kw[key] = False
|
| 969 |
+
super().__init__(**kw)
|
| 970 |
+
for storage in self.storage:
|
| 971 |
+
if not os.path.exists(storage):
|
| 972 |
+
self._makedirs(storage)
|
| 973 |
+
|
| 974 |
+
def _check_file(self, path):
|
| 975 |
+
self._check_cache()
|
| 976 |
+
sha = self._mapper(path)
|
| 977 |
+
for storage in self.storage:
|
| 978 |
+
fn = os.path.join(storage, sha)
|
| 979 |
+
if os.path.exists(fn):
|
| 980 |
+
return fn
|
| 981 |
+
|
| 982 |
+
def save_cache(self):
|
| 983 |
+
pass
|
| 984 |
+
|
| 985 |
+
def load_cache(self):
|
| 986 |
+
pass
|
| 987 |
+
|
| 988 |
+
def clear_expired_cache(self, expiry_time=None):
|
| 989 |
+
"""Remove cached files older than ``expiry_time`` seconds.
|
| 990 |
+
|
| 991 |
+
SimpleCache does not store metadata, so cached file modification times
|
| 992 |
+
are used instead. Only the last (writable) cache location is changed.
|
| 993 |
+
|
| 994 |
+
Parameters
|
| 995 |
+
----------
|
| 996 |
+
expiry_time: int or float
|
| 997 |
+
Maximum age of a cached file in seconds. This must be supplied
|
| 998 |
+
explicitly because SimpleCache has no configured expiry time.
|
| 999 |
+
"""
|
| 1000 |
+
if expiry_time is None:
|
| 1001 |
+
raise ValueError("expiry_time must be provided for simplecache")
|
| 1002 |
+
if expiry_time < 0:
|
| 1003 |
+
raise ValueError("expiry_time must be non-negative")
|
| 1004 |
+
|
| 1005 |
+
self._mkcache()
|
| 1006 |
+
cutoff = time.time() - expiry_time
|
| 1007 |
+
with os.scandir(self.storage[-1]) as entries:
|
| 1008 |
+
for entry in entries:
|
| 1009 |
+
try:
|
| 1010 |
+
if (
|
| 1011 |
+
entry.is_file(follow_symlinks=False)
|
| 1012 |
+
and entry.stat(follow_symlinks=False).st_mtime < cutoff
|
| 1013 |
+
):
|
| 1014 |
+
os.remove(entry.path)
|
| 1015 |
+
except FileNotFoundError:
|
| 1016 |
+
# Another process may be using the same simple cache.
|
| 1017 |
+
pass
|
| 1018 |
+
self._cache_size = None
|
| 1019 |
+
|
| 1020 |
+
async def _check_file_async(self, path):
|
| 1021 |
+
return self._check_file(path) # existence-based, no remote I/O
|
| 1022 |
+
|
| 1023 |
+
async def _download_async(self, path, fn, **kwargs):
|
| 1024 |
+
# no metadata to record (and no ukey lookup needed)
|
| 1025 |
+
kwargs.setdefault("callback", self.callback)
|
| 1026 |
+
with _tempfile(fn) as tmp:
|
| 1027 |
+
await self.fs._get_file(path, tmp, **kwargs)
|
| 1028 |
+
|
| 1029 |
+
def pipe_file(self, path, value=None, **kwargs):
|
| 1030 |
+
if self._intrans:
|
| 1031 |
+
with self.open(path, "wb") as f:
|
| 1032 |
+
f.write(value)
|
| 1033 |
+
else:
|
| 1034 |
+
super().pipe_file(path, value)
|
| 1035 |
+
|
| 1036 |
+
def ls(self, path, detail=True, **kwargs):
|
| 1037 |
+
path = self._strip_protocol(path)
|
| 1038 |
+
details = []
|
| 1039 |
+
try:
|
| 1040 |
+
details = self.fs.ls(
|
| 1041 |
+
path, detail=True, **kwargs
|
| 1042 |
+
).copy() # don't edit original!
|
| 1043 |
+
except FileNotFoundError as e:
|
| 1044 |
+
ex = e
|
| 1045 |
+
else:
|
| 1046 |
+
ex = None
|
| 1047 |
+
if self._intrans:
|
| 1048 |
+
path1 = path.rstrip("/") + "/"
|
| 1049 |
+
for f in self.transaction.files:
|
| 1050 |
+
if f.path == path:
|
| 1051 |
+
details.append(
|
| 1052 |
+
{"name": path, "size": f.size or f.tell(), "type": "file"}
|
| 1053 |
+
)
|
| 1054 |
+
elif f.path.startswith(path1):
|
| 1055 |
+
if f.path.count("/") == path1.count("/"):
|
| 1056 |
+
details.append(
|
| 1057 |
+
{"name": f.path, "size": f.size or f.tell(), "type": "file"}
|
| 1058 |
+
)
|
| 1059 |
+
else:
|
| 1060 |
+
dname = "/".join(f.path.split("/")[: path1.count("/") + 1])
|
| 1061 |
+
details.append({"name": dname, "size": 0, "type": "directory"})
|
| 1062 |
+
if ex is not None and not details:
|
| 1063 |
+
raise ex
|
| 1064 |
+
if detail:
|
| 1065 |
+
return details
|
| 1066 |
+
return sorted(_["name"] for _ in details)
|
| 1067 |
+
|
| 1068 |
+
def info(self, path, **kwargs):
|
| 1069 |
+
path = self._strip_protocol(path)
|
| 1070 |
+
if self._intrans:
|
| 1071 |
+
f = [_ for _ in self.transaction.files if _.path == path]
|
| 1072 |
+
if f:
|
| 1073 |
+
size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell()
|
| 1074 |
+
return {"name": path, "size": size, "type": "file"}
|
| 1075 |
+
f = any(_.path.startswith(path + "/") for _ in self.transaction.files)
|
| 1076 |
+
if f:
|
| 1077 |
+
return {"name": path, "size": 0, "type": "directory"}
|
| 1078 |
+
return self.fs.info(path, **kwargs)
|
| 1079 |
+
|
| 1080 |
+
def pipe(self, path, value=None, **kwargs):
|
| 1081 |
+
if isinstance(path, str):
|
| 1082 |
+
self.pipe_file(self._strip_protocol(path), value, **kwargs)
|
| 1083 |
+
elif isinstance(path, dict):
|
| 1084 |
+
for k, v in path.items():
|
| 1085 |
+
self.pipe_file(self._strip_protocol(k), v, **kwargs)
|
| 1086 |
+
else:
|
| 1087 |
+
raise ValueError("path must be str or dict")
|
| 1088 |
+
|
| 1089 |
+
def cat_ranges(
|
| 1090 |
+
self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
|
| 1091 |
+
):
|
| 1092 |
+
logger.debug("cat ranges %s", paths)
|
| 1093 |
+
lpaths, rpaths, download = self._local_paths_for_ranges(paths)
|
| 1094 |
+
if download:
|
| 1095 |
+
_atomic_get(self.fs, rpaths, download, callback=self.callback)
|
| 1096 |
+
return LocalFileSystem().cat_ranges(
|
| 1097 |
+
lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
|
| 1098 |
+
)
|
| 1099 |
+
|
| 1100 |
+
def _get_cached_file_before_open(self, path, **kwargs):
|
| 1101 |
+
sha = self._mapper(path)
|
| 1102 |
+
fn = os.path.join(self.storage[-1], sha)
|
| 1103 |
+
logger.debug("Copying %s to local cache", path)
|
| 1104 |
+
|
| 1105 |
+
self._mkcache()
|
| 1106 |
+
self._cache_size = None
|
| 1107 |
+
|
| 1108 |
+
if self.compression:
|
| 1109 |
+
with (
|
| 1110 |
+
_tempfile(fn) as tmp,
|
| 1111 |
+
self.fs._open(path, mode="rb", **kwargs) as f,
|
| 1112 |
+
open(tmp, "wb") as f2,
|
| 1113 |
+
):
|
| 1114 |
+
if isinstance(f, AbstractBufferedFile):
|
| 1115 |
+
# want no type of caching if just downloading whole thing
|
| 1116 |
+
f.cache = BaseCache(0, f.cache.fetcher, f.size)
|
| 1117 |
+
comp = (
|
| 1118 |
+
infer_compression(path)
|
| 1119 |
+
if self.compression == "infer"
|
| 1120 |
+
else self.compression
|
| 1121 |
+
)
|
| 1122 |
+
f = compr[comp](f, mode="rb")
|
| 1123 |
+
data = True
|
| 1124 |
+
while data:
|
| 1125 |
+
block = getattr(f, "blocksize", 5 * 2**20)
|
| 1126 |
+
data = f.read(block)
|
| 1127 |
+
f2.write(data)
|
| 1128 |
+
else:
|
| 1129 |
+
with _tempfile(fn) as tmp:
|
| 1130 |
+
self.fs.get_file(path, tmp, callback=self.callback)
|
| 1131 |
+
|
| 1132 |
+
def _open(self, path, mode="rb", **kwargs):
|
| 1133 |
+
path = self._strip_protocol(path)
|
| 1134 |
+
sha = self._mapper(path)
|
| 1135 |
+
|
| 1136 |
+
# For read (or append), (try) download from remote
|
| 1137 |
+
if "r" in mode or "a" in mode:
|
| 1138 |
+
if not self._check_file(path):
|
| 1139 |
+
# append does not require an existing file but read does
|
| 1140 |
+
if self.fs.exists(path):
|
| 1141 |
+
self._get_cached_file_before_open(path, **kwargs)
|
| 1142 |
+
elif "r" in mode:
|
| 1143 |
+
raise FileNotFoundError(path)
|
| 1144 |
+
|
| 1145 |
+
fn = self._check_file(path)
|
| 1146 |
+
# Just reading does not need special file handling
|
| 1147 |
+
if "r" in mode and "+" not in mode:
|
| 1148 |
+
return open(fn, mode)
|
| 1149 |
+
|
| 1150 |
+
fn = os.path.join(self.storage[-1], sha)
|
| 1151 |
+
user_specified_kwargs = {
|
| 1152 |
+
k: v
|
| 1153 |
+
for k, v in kwargs.items()
|
| 1154 |
+
if k not in ["autocommit", "block_size", "cache_options"]
|
| 1155 |
+
} # those were added by open()
|
| 1156 |
+
return LocalTempFile(
|
| 1157 |
+
self,
|
| 1158 |
+
path,
|
| 1159 |
+
mode=mode,
|
| 1160 |
+
autocommit=not self._intrans,
|
| 1161 |
+
fn=fn,
|
| 1162 |
+
**user_specified_kwargs,
|
| 1163 |
+
)
|
| 1164 |
+
|
| 1165 |
+
|
| 1166 |
+
class LocalTempFile:
|
| 1167 |
+
"""A temporary local file, which will be uploaded on commit"""
|
| 1168 |
+
|
| 1169 |
+
def __init__(self, fs, path, fn, mode="wb", autocommit=True, seek=0, **kwargs):
|
| 1170 |
+
self.fn = fn
|
| 1171 |
+
self.fh = open(fn, mode)
|
| 1172 |
+
self.mode = mode
|
| 1173 |
+
if seek:
|
| 1174 |
+
self.fh.seek(seek)
|
| 1175 |
+
self.path = path
|
| 1176 |
+
self.size = None
|
| 1177 |
+
self.fs = fs
|
| 1178 |
+
self.closed = False
|
| 1179 |
+
self.autocommit = autocommit
|
| 1180 |
+
self.kwargs = kwargs
|
| 1181 |
+
|
| 1182 |
+
def __reduce__(self):
|
| 1183 |
+
# always open in r+b to allow continuing writing at a location
|
| 1184 |
+
return (
|
| 1185 |
+
LocalTempFile,
|
| 1186 |
+
(self.fs, self.path, self.fn, "r+b", self.autocommit, self.tell()),
|
| 1187 |
+
)
|
| 1188 |
+
|
| 1189 |
+
def __enter__(self):
|
| 1190 |
+
return self.fh
|
| 1191 |
+
|
| 1192 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 1193 |
+
self.close()
|
| 1194 |
+
|
| 1195 |
+
def close(self):
|
| 1196 |
+
# self.size = self.fh.tell()
|
| 1197 |
+
if self.closed:
|
| 1198 |
+
return
|
| 1199 |
+
self.fh.close()
|
| 1200 |
+
self.closed = True
|
| 1201 |
+
if self.autocommit:
|
| 1202 |
+
self.commit()
|
| 1203 |
+
|
| 1204 |
+
def discard(self):
|
| 1205 |
+
self.fh.close()
|
| 1206 |
+
# Repeated writes in one transaction can share a cache filename.
|
| 1207 |
+
with suppress(FileNotFoundError):
|
| 1208 |
+
os.remove(self.fn)
|
| 1209 |
+
|
| 1210 |
+
def commit(self):
|
| 1211 |
+
# calling put() with list arguments avoids path expansion and additional operations
|
| 1212 |
+
# like isdir()
|
| 1213 |
+
self.fs.put([self.fn], [self.path], **self.kwargs)
|
| 1214 |
+
# we do not delete the local copy, it's still in the cache.
|
| 1215 |
+
|
| 1216 |
+
@property
|
| 1217 |
+
def name(self):
|
| 1218 |
+
return self.fn
|
| 1219 |
+
|
| 1220 |
+
def __repr__(self) -> str:
|
| 1221 |
+
return f"LocalTempFile: {self.path}"
|
| 1222 |
+
|
| 1223 |
+
def __getattr__(self, item):
|
| 1224 |
+
return getattr(self.fh, item)
|
tasks/tasksmith-3bb3c78392c6/tests/source/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"
|
tasks/tasksmith-3bb3c78392c6/tests/source/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)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/data.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import io
|
| 3 |
+
from urllib.parse import unquote_to_bytes
|
| 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 |
+
# Strip the fragment before decoding so an encoded %23 remains data.
|
| 42 |
+
pref, data = path.split("#", 1)[0].split(",", 1)
|
| 43 |
+
if pref.endswith(";base64"):
|
| 44 |
+
return base64.b64decode(unquote_to_bytes(data))[start:end]
|
| 45 |
+
return unquote_to_bytes(data)[start:end]
|
| 46 |
+
|
| 47 |
+
def info(self, path, **kwargs):
|
| 48 |
+
path = self._strip_protocol(path)
|
| 49 |
+
pref, name = path.split(",", 1)
|
| 50 |
+
data = self.cat_file(path)
|
| 51 |
+
mime = pref.split(";", 1)[0]
|
| 52 |
+
return {"name": name, "size": len(data), "type": "file", "mimetype": mime}
|
| 53 |
+
|
| 54 |
+
def _open(
|
| 55 |
+
self,
|
| 56 |
+
path,
|
| 57 |
+
mode="rb",
|
| 58 |
+
block_size=None,
|
| 59 |
+
autocommit=True,
|
| 60 |
+
cache_options=None,
|
| 61 |
+
**kwargs,
|
| 62 |
+
):
|
| 63 |
+
if "r" not in mode:
|
| 64 |
+
raise ValueError("Read only filesystem")
|
| 65 |
+
return io.BytesIO(self.cat_file(path))
|
| 66 |
+
|
| 67 |
+
@staticmethod
|
| 68 |
+
def encode(data: bytes, mime: str | None = None):
|
| 69 |
+
"""Format the given data into data-URL syntax
|
| 70 |
+
|
| 71 |
+
This version always base64 encodes, even when the data is ascii/url-safe.
|
| 72 |
+
"""
|
| 73 |
+
return f"data:{mime or ''};base64,{base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
|
|
| 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 |
+
while True:
|
| 189 |
+
try:
|
| 190 |
+
self._send_to_api(
|
| 191 |
+
method="post",
|
| 192 |
+
endpoint="delete",
|
| 193 |
+
json={"path": path, "recursive": recursive},
|
| 194 |
+
)
|
| 195 |
+
except DatabricksException as e:
|
| 196 |
+
# Not everything was deleted so far; retry without recursion.
|
| 197 |
+
if e.error_code == "PARTIAL_DELETE":
|
| 198 |
+
continue
|
| 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 |
+
break
|
| 205 |
+
self.invalidate_cache(self._parent(path))
|
| 206 |
+
|
| 207 |
+
def mv(
|
| 208 |
+
self, source_path, destination_path, recursive=False, maxdepth=None, **kwargs
|
| 209 |
+
):
|
| 210 |
+
"""
|
| 211 |
+
Move a source to a destination path.
|
| 212 |
+
|
| 213 |
+
A note from the original [databricks API manual]
|
| 214 |
+
(https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move).
|
| 215 |
+
|
| 216 |
+
When moving a large number of files the API call will time out after
|
| 217 |
+
approximately 60s, potentially resulting in partially moved data.
|
| 218 |
+
Therefore, for operations that move more than 10k files, we strongly
|
| 219 |
+
discourage using the DBFS REST API.
|
| 220 |
+
|
| 221 |
+
Parameters
|
| 222 |
+
----------
|
| 223 |
+
source_path: str
|
| 224 |
+
From where to move (absolute path)
|
| 225 |
+
destination_path: str
|
| 226 |
+
To where to move (absolute path)
|
| 227 |
+
recursive: bool
|
| 228 |
+
Not implemented to far.
|
| 229 |
+
maxdepth:
|
| 230 |
+
Not implemented to far.
|
| 231 |
+
"""
|
| 232 |
+
if recursive:
|
| 233 |
+
raise NotImplementedError
|
| 234 |
+
if maxdepth:
|
| 235 |
+
raise NotImplementedError
|
| 236 |
+
|
| 237 |
+
try:
|
| 238 |
+
self._send_to_api(
|
| 239 |
+
method="post",
|
| 240 |
+
endpoint="move",
|
| 241 |
+
json={"source_path": source_path, "destination_path": destination_path},
|
| 242 |
+
)
|
| 243 |
+
except DatabricksException as e:
|
| 244 |
+
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
|
| 245 |
+
raise FileNotFoundError(e.message) from e
|
| 246 |
+
elif e.error_code == "RESOURCE_ALREADY_EXISTS":
|
| 247 |
+
raise FileExistsError(e.message) from e
|
| 248 |
+
|
| 249 |
+
raise
|
| 250 |
+
self.invalidate_cache(self._parent(source_path))
|
| 251 |
+
self.invalidate_cache(self._parent(destination_path))
|
| 252 |
+
|
| 253 |
+
def _open(self, path, mode="rb", block_size="default", **kwargs):
|
| 254 |
+
"""
|
| 255 |
+
Overwrite the base class method to make sure to create a DBFile.
|
| 256 |
+
All arguments are copied from the base method.
|
| 257 |
+
|
| 258 |
+
Only the default blocksize is allowed.
|
| 259 |
+
"""
|
| 260 |
+
return DatabricksFile(self, path, mode=mode, block_size=block_size, **kwargs)
|
| 261 |
+
|
| 262 |
+
def _send_to_api(self, method, endpoint, json):
|
| 263 |
+
"""
|
| 264 |
+
Send the given json to the DBFS API
|
| 265 |
+
using a get or post request (specified by the argument `method`).
|
| 266 |
+
|
| 267 |
+
Parameters
|
| 268 |
+
----------
|
| 269 |
+
method: str
|
| 270 |
+
Which http method to use for communication; "get" or "post".
|
| 271 |
+
endpoint: str
|
| 272 |
+
Where to send the request to (last part of the API URL)
|
| 273 |
+
json: dict
|
| 274 |
+
Dictionary of information to send
|
| 275 |
+
"""
|
| 276 |
+
if method == "post":
|
| 277 |
+
session_call = self.session.post
|
| 278 |
+
elif method == "get":
|
| 279 |
+
session_call = self.session.get
|
| 280 |
+
else:
|
| 281 |
+
raise ValueError(f"Do not understand method {method}")
|
| 282 |
+
|
| 283 |
+
url = urllib.parse.urljoin(f"https://{self.instance}/api/2.0/dbfs/", endpoint)
|
| 284 |
+
|
| 285 |
+
r = session_call(url, json=json)
|
| 286 |
+
|
| 287 |
+
# The DBFS API will return a json, also in case of an exception.
|
| 288 |
+
# We want to preserve this information as good as possible.
|
| 289 |
+
try:
|
| 290 |
+
r.raise_for_status()
|
| 291 |
+
except requests.HTTPError as e:
|
| 292 |
+
# try to extract json error message
|
| 293 |
+
# if that fails, fall back to the original exception
|
| 294 |
+
try:
|
| 295 |
+
exception_json = e.response.json()
|
| 296 |
+
except Exception:
|
| 297 |
+
raise e from None
|
| 298 |
+
|
| 299 |
+
raise DatabricksException(**exception_json) from e
|
| 300 |
+
|
| 301 |
+
return r.json()
|
| 302 |
+
|
| 303 |
+
def _create_handle(self, path, overwrite=True):
|
| 304 |
+
"""
|
| 305 |
+
Internal function to create a handle, which can be used to
|
| 306 |
+
write blocks of a file to DBFS.
|
| 307 |
+
A handle has a unique identifier which needs to be passed
|
| 308 |
+
whenever written during this transaction.
|
| 309 |
+
The handle is active for 10 minutes - after that a new
|
| 310 |
+
write transaction needs to be created.
|
| 311 |
+
Make sure to close the handle after you are finished.
|
| 312 |
+
|
| 313 |
+
Parameters
|
| 314 |
+
----------
|
| 315 |
+
path: str
|
| 316 |
+
Absolute path for this file.
|
| 317 |
+
overwrite: bool
|
| 318 |
+
If a file already exist at this location, either overwrite
|
| 319 |
+
it or raise an exception.
|
| 320 |
+
"""
|
| 321 |
+
try:
|
| 322 |
+
r = self._send_to_api(
|
| 323 |
+
method="post",
|
| 324 |
+
endpoint="create",
|
| 325 |
+
json={"path": path, "overwrite": overwrite},
|
| 326 |
+
)
|
| 327 |
+
return r["handle"]
|
| 328 |
+
except DatabricksException as e:
|
| 329 |
+
if e.error_code == "RESOURCE_ALREADY_EXISTS":
|
| 330 |
+
raise FileExistsError(e.message) from e
|
| 331 |
+
|
| 332 |
+
raise
|
| 333 |
+
|
| 334 |
+
def _close_handle(self, handle):
|
| 335 |
+
"""
|
| 336 |
+
Close a handle, which was opened by :func:`_create_handle`.
|
| 337 |
+
|
| 338 |
+
Parameters
|
| 339 |
+
----------
|
| 340 |
+
handle: str
|
| 341 |
+
Which handle to close.
|
| 342 |
+
"""
|
| 343 |
+
try:
|
| 344 |
+
self._send_to_api(method="post", endpoint="close", json={"handle": handle})
|
| 345 |
+
except DatabricksException as e:
|
| 346 |
+
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
|
| 347 |
+
raise FileNotFoundError(e.message) from e
|
| 348 |
+
|
| 349 |
+
raise
|
| 350 |
+
|
| 351 |
+
def _add_data(self, handle, data):
|
| 352 |
+
"""
|
| 353 |
+
Upload data to an already opened file handle
|
| 354 |
+
(opened by :func:`_create_handle`).
|
| 355 |
+
The maximal allowed data size is 1MB after
|
| 356 |
+
conversion to base64.
|
| 357 |
+
Remember to close the handle when you are finished.
|
| 358 |
+
|
| 359 |
+
Parameters
|
| 360 |
+
----------
|
| 361 |
+
handle: str
|
| 362 |
+
Which handle to upload data to.
|
| 363 |
+
data: bytes
|
| 364 |
+
Block of data to add to the handle.
|
| 365 |
+
"""
|
| 366 |
+
data = base64.b64encode(data).decode()
|
| 367 |
+
try:
|
| 368 |
+
self._send_to_api(
|
| 369 |
+
method="post",
|
| 370 |
+
endpoint="add-block",
|
| 371 |
+
json={"handle": handle, "data": data},
|
| 372 |
+
)
|
| 373 |
+
except DatabricksException as e:
|
| 374 |
+
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
|
| 375 |
+
raise FileNotFoundError(e.message) from e
|
| 376 |
+
elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED":
|
| 377 |
+
raise ValueError(e.message) from e
|
| 378 |
+
|
| 379 |
+
raise
|
| 380 |
+
|
| 381 |
+
def _get_data(self, path, start, end):
|
| 382 |
+
"""
|
| 383 |
+
Download data in bytes from a given absolute path in a block
|
| 384 |
+
from [start, start+length].
|
| 385 |
+
The maximum number of allowed bytes to read is 1MB.
|
| 386 |
+
|
| 387 |
+
Parameters
|
| 388 |
+
----------
|
| 389 |
+
path: str
|
| 390 |
+
Absolute path to download data from
|
| 391 |
+
start: int
|
| 392 |
+
Start position of the block
|
| 393 |
+
end: int
|
| 394 |
+
End position of the block
|
| 395 |
+
"""
|
| 396 |
+
try:
|
| 397 |
+
r = self._send_to_api(
|
| 398 |
+
method="get",
|
| 399 |
+
endpoint="read",
|
| 400 |
+
json={"path": path, "offset": start, "length": end - start},
|
| 401 |
+
)
|
| 402 |
+
return base64.b64decode(r["data"])
|
| 403 |
+
except DatabricksException as e:
|
| 404 |
+
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
|
| 405 |
+
raise FileNotFoundError(e.message) from e
|
| 406 |
+
elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]:
|
| 407 |
+
raise ValueError(e.message) from e
|
| 408 |
+
|
| 409 |
+
raise
|
| 410 |
+
|
| 411 |
+
def invalidate_cache(self, path=None):
|
| 412 |
+
if path is None:
|
| 413 |
+
self.dircache.clear()
|
| 414 |
+
else:
|
| 415 |
+
self.dircache.pop(path, None)
|
| 416 |
+
super().invalidate_cache(path)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class DatabricksFile(AbstractBufferedFile):
|
| 420 |
+
"""
|
| 421 |
+
Helper class for files referenced in the DatabricksFileSystem.
|
| 422 |
+
"""
|
| 423 |
+
|
| 424 |
+
DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size
|
| 425 |
+
|
| 426 |
+
def __init__(
|
| 427 |
+
self,
|
| 428 |
+
fs,
|
| 429 |
+
path,
|
| 430 |
+
mode="rb",
|
| 431 |
+
block_size="default",
|
| 432 |
+
autocommit=True,
|
| 433 |
+
cache_type="readahead",
|
| 434 |
+
cache_options=None,
|
| 435 |
+
**kwargs,
|
| 436 |
+
):
|
| 437 |
+
"""
|
| 438 |
+
Create a new instance of the DatabricksFile.
|
| 439 |
+
|
| 440 |
+
The blocksize needs to be the default one.
|
| 441 |
+
"""
|
| 442 |
+
if block_size is None or block_size == "default":
|
| 443 |
+
block_size = self.DEFAULT_BLOCK_SIZE
|
| 444 |
+
|
| 445 |
+
if block_size != self.DEFAULT_BLOCK_SIZE:
|
| 446 |
+
raise ValueError(
|
| 447 |
+
f"Only the default block size is allowed, not {block_size}"
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
super().__init__(
|
| 451 |
+
fs,
|
| 452 |
+
path,
|
| 453 |
+
mode=mode,
|
| 454 |
+
block_size=block_size,
|
| 455 |
+
autocommit=autocommit,
|
| 456 |
+
cache_type=cache_type,
|
| 457 |
+
cache_options=cache_options or {},
|
| 458 |
+
**kwargs,
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
def _initiate_upload(self):
|
| 462 |
+
"""Internal function to start a file upload"""
|
| 463 |
+
self.handle = self.fs._create_handle(self.path, overwrite="x" not in self.mode)
|
| 464 |
+
|
| 465 |
+
def _upload_chunk(self, final=False):
|
| 466 |
+
"""Internal function to add a chunk of data to a started upload"""
|
| 467 |
+
self.buffer.seek(0)
|
| 468 |
+
data = self.buffer.getvalue()
|
| 469 |
+
|
| 470 |
+
data_chunks = [
|
| 471 |
+
data[start:end] for start, end in self._to_sized_blocks(len(data))
|
| 472 |
+
]
|
| 473 |
+
|
| 474 |
+
for data_chunk in data_chunks:
|
| 475 |
+
self.fs._add_data(handle=self.handle, data=data_chunk)
|
| 476 |
+
|
| 477 |
+
if final:
|
| 478 |
+
self.fs._close_handle(handle=self.handle)
|
| 479 |
+
return True
|
| 480 |
+
|
| 481 |
+
def _fetch_range(self, start, end):
|
| 482 |
+
"""Internal function to download a block of data"""
|
| 483 |
+
return_buffer = b""
|
| 484 |
+
length = end - start
|
| 485 |
+
for chunk_start, chunk_end in self._to_sized_blocks(length, start):
|
| 486 |
+
return_buffer += self.fs._get_data(
|
| 487 |
+
path=self.path, start=chunk_start, end=chunk_end
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
return return_buffer
|
| 491 |
+
|
| 492 |
+
def _to_sized_blocks(self, length, start=0):
|
| 493 |
+
"""Helper function to split a range from 0 to total_length into blocksizes"""
|
| 494 |
+
end = start + length
|
| 495 |
+
for data_chunk in range(start, end, self.blocksize):
|
| 496 |
+
data_start = data_chunk
|
| 497 |
+
data_end = min(end, data_chunk + self.blocksize)
|
| 498 |
+
yield data_start, data_end
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/dirfs.py
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .. import filesystem
|
| 2 |
+
from ..asyn import AsyncFileSystem
|
| 3 |
+
from ..utils import stringify_path
|
| 4 |
+
from .chained import ChainedFileSystem
|
| 5 |
+
from .local import LocalFileSystem
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _escapes_root(path):
|
| 9 |
+
"""Whether a relative path would resolve above its root via ".." segments."""
|
| 10 |
+
depth = 0
|
| 11 |
+
for part in path.split("/"):
|
| 12 |
+
if part == "..":
|
| 13 |
+
depth -= 1
|
| 14 |
+
if depth < 0:
|
| 15 |
+
return True
|
| 16 |
+
elif part and part != ".":
|
| 17 |
+
depth += 1
|
| 18 |
+
return False
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class DirFileSystem(AsyncFileSystem, ChainedFileSystem):
|
| 22 |
+
"""Directory prefix filesystem
|
| 23 |
+
|
| 24 |
+
The DirFileSystem is a filesystem-wrapper. It assumes every path it is dealing with
|
| 25 |
+
is relative to the `path`. After performing the necessary paths operation it
|
| 26 |
+
delegates everything to the wrapped filesystem.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
protocol = "dir"
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
path=None,
|
| 34 |
+
fs=None,
|
| 35 |
+
fo=None,
|
| 36 |
+
target_protocol=None,
|
| 37 |
+
target_options=None,
|
| 38 |
+
**storage_options,
|
| 39 |
+
):
|
| 40 |
+
"""
|
| 41 |
+
Parameters
|
| 42 |
+
----------
|
| 43 |
+
path: str
|
| 44 |
+
Path to the directory.
|
| 45 |
+
fs: AbstractFileSystem
|
| 46 |
+
An instantiated filesystem to wrap.
|
| 47 |
+
target_protocol, target_options:
|
| 48 |
+
if fs is none, construct it from these
|
| 49 |
+
fo: str
|
| 50 |
+
Alternate for path; do not provide both
|
| 51 |
+
"""
|
| 52 |
+
super().__init__(**storage_options)
|
| 53 |
+
if fs is None:
|
| 54 |
+
fs = filesystem(protocol=target_protocol, **(target_options or {}))
|
| 55 |
+
path = path or fo
|
| 56 |
+
|
| 57 |
+
if self.asynchronous and not fs.async_impl:
|
| 58 |
+
raise ValueError("can't use asynchronous with non-async fs")
|
| 59 |
+
|
| 60 |
+
if fs.async_impl and self.asynchronous != fs.asynchronous:
|
| 61 |
+
raise ValueError("both dirfs and fs should be in the same sync/async mode")
|
| 62 |
+
|
| 63 |
+
self.path = fs._strip_protocol(path)
|
| 64 |
+
self.fs = fs
|
| 65 |
+
self.async_impl = fs.async_impl
|
| 66 |
+
|
| 67 |
+
def _join(self, path):
|
| 68 |
+
path = stringify_path(path)
|
| 69 |
+
if isinstance(path, str):
|
| 70 |
+
if not self.path:
|
| 71 |
+
return path
|
| 72 |
+
if not path:
|
| 73 |
+
return self.path
|
| 74 |
+
# a trailing slash requests "copy the contents" in bulk
|
| 75 |
+
# operations (docs/source/copying.rst), so preserve it across the
|
| 76 |
+
# join even though _strip_protocol removes it
|
| 77 |
+
suffix = "/" if path.endswith("/") else ""
|
| 78 |
+
path = self._strip_protocol(path)
|
| 79 |
+
# ".." only navigates above the root on filesystems that resolve it
|
| 80 |
+
# against a real directory tree; on object stores it is a literal
|
| 81 |
+
# path part, so only guard the local case here.
|
| 82 |
+
if isinstance(self.fs, LocalFileSystem) and _escapes_root(path):
|
| 83 |
+
raise ValueError(
|
| 84 |
+
f"path {path!r} escapes the {self.path!r} root of the filesystem"
|
| 85 |
+
)
|
| 86 |
+
joined = self.fs.sep.join((self.path, path))
|
| 87 |
+
if suffix and not joined.endswith("/"):
|
| 88 |
+
joined += "/"
|
| 89 |
+
return joined
|
| 90 |
+
if isinstance(path, dict):
|
| 91 |
+
return {self._join(_path): value for _path, value in path.items()}
|
| 92 |
+
return [self._join(_path) for _path in path]
|
| 93 |
+
|
| 94 |
+
def _relpath(self, path):
|
| 95 |
+
if isinstance(path, str):
|
| 96 |
+
if not self.path:
|
| 97 |
+
return path
|
| 98 |
+
# We need to account for S3FileSystem returning paths that do not
|
| 99 |
+
# start with a '/'
|
| 100 |
+
if path == self.path or (
|
| 101 |
+
self.path.startswith(self.fs.sep) and path == self.path[1:]
|
| 102 |
+
):
|
| 103 |
+
return ""
|
| 104 |
+
prefix = self.path + self.fs.sep
|
| 105 |
+
if self.path.startswith(self.fs.sep) and not path.startswith(self.fs.sep):
|
| 106 |
+
prefix = prefix[1:]
|
| 107 |
+
assert path.startswith(prefix)
|
| 108 |
+
return path[len(prefix) :]
|
| 109 |
+
return [self._relpath(_path) for _path in path]
|
| 110 |
+
|
| 111 |
+
def _relpath_detail(self, paths):
|
| 112 |
+
out = {}
|
| 113 |
+
for path, info in paths.items():
|
| 114 |
+
path = self._relpath(path)
|
| 115 |
+
info = info.copy()
|
| 116 |
+
info["name"] = path
|
| 117 |
+
out[path] = info
|
| 118 |
+
return out
|
| 119 |
+
|
| 120 |
+
# Wrappers below
|
| 121 |
+
|
| 122 |
+
@property
|
| 123 |
+
def sep(self):
|
| 124 |
+
return self.fs.sep
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def local_file(self):
|
| 128 |
+
return getattr(self.fs, "local_file", False)
|
| 129 |
+
|
| 130 |
+
async def set_session(self, *args, **kwargs):
|
| 131 |
+
return await self.fs.set_session(*args, **kwargs)
|
| 132 |
+
|
| 133 |
+
async def _rm_file(self, path, **kwargs):
|
| 134 |
+
return await self.fs._rm_file(self._join(path), **kwargs)
|
| 135 |
+
|
| 136 |
+
def rm_file(self, path, **kwargs):
|
| 137 |
+
return self.fs.rm_file(self._join(path), **kwargs)
|
| 138 |
+
|
| 139 |
+
async def _rm(self, path, *args, **kwargs):
|
| 140 |
+
return await self.fs._rm(self._join(path), *args, **kwargs)
|
| 141 |
+
|
| 142 |
+
def rm(self, path, *args, **kwargs):
|
| 143 |
+
return self.fs.rm(self._join(path), *args, **kwargs)
|
| 144 |
+
|
| 145 |
+
def delete(self, path, recursive=False, maxdepth=None):
|
| 146 |
+
return self.fs.delete(self._join(path), recursive=recursive, maxdepth=maxdepth)
|
| 147 |
+
|
| 148 |
+
async def _cp_file(self, path1, path2, **kwargs):
|
| 149 |
+
return await self.fs._cp_file(self._join(path1), self._join(path2), **kwargs)
|
| 150 |
+
|
| 151 |
+
def cp_file(self, path1, path2, **kwargs):
|
| 152 |
+
return self.fs.cp_file(self._join(path1), self._join(path2), **kwargs)
|
| 153 |
+
|
| 154 |
+
async def _copy(
|
| 155 |
+
self,
|
| 156 |
+
path1,
|
| 157 |
+
path2,
|
| 158 |
+
*args,
|
| 159 |
+
**kwargs,
|
| 160 |
+
):
|
| 161 |
+
return await self.fs._copy(
|
| 162 |
+
self._join(path1),
|
| 163 |
+
self._join(path2),
|
| 164 |
+
*args,
|
| 165 |
+
**kwargs,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
def copy(self, path1, path2, *args, **kwargs):
|
| 169 |
+
return self.fs.copy(
|
| 170 |
+
self._join(path1),
|
| 171 |
+
self._join(path2),
|
| 172 |
+
*args,
|
| 173 |
+
**kwargs,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
async def _pipe(self, path, *args, **kwargs):
|
| 177 |
+
return await self.fs._pipe(self._join(path), *args, **kwargs)
|
| 178 |
+
|
| 179 |
+
def pipe(self, path, *args, **kwargs):
|
| 180 |
+
return self.fs.pipe(self._join(path), *args, **kwargs)
|
| 181 |
+
|
| 182 |
+
async def _pipe_file(self, path, *args, **kwargs):
|
| 183 |
+
return await self.fs._pipe_file(self._join(path), *args, **kwargs)
|
| 184 |
+
|
| 185 |
+
def pipe_file(self, path, *args, **kwargs):
|
| 186 |
+
return self.fs.pipe_file(self._join(path), *args, **kwargs)
|
| 187 |
+
|
| 188 |
+
def write_text(
|
| 189 |
+
self, path, value, encoding=None, errors=None, newline=None, **kwargs
|
| 190 |
+
):
|
| 191 |
+
return self.fs.write_text(
|
| 192 |
+
self._join(path),
|
| 193 |
+
value,
|
| 194 |
+
encoding=encoding,
|
| 195 |
+
errors=errors,
|
| 196 |
+
newline=newline,
|
| 197 |
+
**kwargs,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
async def _cat_file(self, path, *args, **kwargs):
|
| 201 |
+
return await self.fs._cat_file(self._join(path), *args, **kwargs)
|
| 202 |
+
|
| 203 |
+
def cat_file(self, path, *args, **kwargs):
|
| 204 |
+
return self.fs.cat_file(self._join(path), *args, **kwargs)
|
| 205 |
+
|
| 206 |
+
async def _cat(self, path, *args, **kwargs):
|
| 207 |
+
ret = await self.fs._cat(
|
| 208 |
+
self._join(path),
|
| 209 |
+
*args,
|
| 210 |
+
**kwargs,
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
if isinstance(ret, dict):
|
| 214 |
+
return {self._relpath(key): value for key, value in ret.items()}
|
| 215 |
+
|
| 216 |
+
return ret
|
| 217 |
+
|
| 218 |
+
def cat(self, path, *args, **kwargs):
|
| 219 |
+
ret = self.fs.cat(
|
| 220 |
+
self._join(path),
|
| 221 |
+
*args,
|
| 222 |
+
**kwargs,
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
if isinstance(ret, dict):
|
| 226 |
+
return {self._relpath(key): value for key, value in ret.items()}
|
| 227 |
+
|
| 228 |
+
return ret
|
| 229 |
+
|
| 230 |
+
async def _cat_ranges(self, paths, starts, ends, *args, **kwargs):
|
| 231 |
+
return await self.fs._cat_ranges(
|
| 232 |
+
self._join(paths), starts, ends, *args, **kwargs
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
def cat_ranges(self, paths, starts, ends, *args, **kwargs):
|
| 236 |
+
return self.fs.cat_ranges(self._join(paths), starts, ends, *args, **kwargs)
|
| 237 |
+
|
| 238 |
+
async def _put_file(self, lpath, rpath, **kwargs):
|
| 239 |
+
return await self.fs._put_file(lpath, self._join(rpath), **kwargs)
|
| 240 |
+
|
| 241 |
+
def put_file(self, lpath, rpath, **kwargs):
|
| 242 |
+
return self.fs.put_file(lpath, self._join(rpath), **kwargs)
|
| 243 |
+
|
| 244 |
+
async def _put(
|
| 245 |
+
self,
|
| 246 |
+
lpath,
|
| 247 |
+
rpath,
|
| 248 |
+
*args,
|
| 249 |
+
**kwargs,
|
| 250 |
+
):
|
| 251 |
+
return await self.fs._put(
|
| 252 |
+
lpath,
|
| 253 |
+
self._join(rpath),
|
| 254 |
+
*args,
|
| 255 |
+
**kwargs,
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
def put(self, lpath, rpath, *args, **kwargs):
|
| 259 |
+
return self.fs.put(
|
| 260 |
+
lpath,
|
| 261 |
+
self._join(rpath),
|
| 262 |
+
*args,
|
| 263 |
+
**kwargs,
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
async def _get_file(self, rpath, lpath, **kwargs):
|
| 267 |
+
return await self.fs._get_file(self._join(rpath), lpath, **kwargs)
|
| 268 |
+
|
| 269 |
+
def get_file(self, rpath, lpath, **kwargs):
|
| 270 |
+
return self.fs.get_file(self._join(rpath), lpath, **kwargs)
|
| 271 |
+
|
| 272 |
+
async def _get(self, rpath, *args, **kwargs):
|
| 273 |
+
return await self.fs._get(self._join(rpath), *args, **kwargs)
|
| 274 |
+
|
| 275 |
+
def get(self, rpath, *args, **kwargs):
|
| 276 |
+
return self.fs.get(self._join(rpath), *args, **kwargs)
|
| 277 |
+
|
| 278 |
+
async def _isfile(self, path):
|
| 279 |
+
return await self.fs._isfile(self._join(path))
|
| 280 |
+
|
| 281 |
+
def isfile(self, path):
|
| 282 |
+
return self.fs.isfile(self._join(path))
|
| 283 |
+
|
| 284 |
+
async def _isdir(self, path):
|
| 285 |
+
return await self.fs._isdir(self._join(path))
|
| 286 |
+
|
| 287 |
+
def isdir(self, path):
|
| 288 |
+
return self.fs.isdir(self._join(path))
|
| 289 |
+
|
| 290 |
+
async def _size(self, path):
|
| 291 |
+
return await self.fs._size(self._join(path))
|
| 292 |
+
|
| 293 |
+
def size(self, path):
|
| 294 |
+
return self.fs.size(self._join(path))
|
| 295 |
+
|
| 296 |
+
async def _sizes(self, paths):
|
| 297 |
+
return await self.fs._sizes(self._join(paths))
|
| 298 |
+
|
| 299 |
+
def sizes(self, paths):
|
| 300 |
+
return self.fs.sizes(self._join(paths))
|
| 301 |
+
|
| 302 |
+
def invalidate_cache(self, path=None):
|
| 303 |
+
# With no path, clear only what is cached under this directory. An
|
| 304 |
+
# unrooted dirfs joins to "", which means everything on the wrapped fs.
|
| 305 |
+
self.fs.invalidate_cache(self._join(path or "") or None)
|
| 306 |
+
|
| 307 |
+
def ukey(self, path):
|
| 308 |
+
return self.fs.ukey(self._join(path))
|
| 309 |
+
|
| 310 |
+
def checksum(self, path):
|
| 311 |
+
return self.fs.checksum(self._join(path))
|
| 312 |
+
|
| 313 |
+
async def _exists(self, path):
|
| 314 |
+
return await self.fs._exists(self._join(path))
|
| 315 |
+
|
| 316 |
+
def exists(self, path):
|
| 317 |
+
return self.fs.exists(self._join(path))
|
| 318 |
+
|
| 319 |
+
async def _info(self, path, **kwargs):
|
| 320 |
+
info = await self.fs._info(self._join(path), **kwargs)
|
| 321 |
+
info = info.copy()
|
| 322 |
+
info["name"] = self._relpath(info["name"])
|
| 323 |
+
return info
|
| 324 |
+
|
| 325 |
+
def info(self, path, **kwargs):
|
| 326 |
+
info = self.fs.info(self._join(path), **kwargs)
|
| 327 |
+
info = info.copy()
|
| 328 |
+
info["name"] = self._relpath(info["name"])
|
| 329 |
+
return info
|
| 330 |
+
|
| 331 |
+
async def _ls(self, path, detail=True, **kwargs):
|
| 332 |
+
ret = (await self.fs._ls(self._join(path), detail=detail, **kwargs)).copy()
|
| 333 |
+
if detail:
|
| 334 |
+
out = []
|
| 335 |
+
for entry in ret:
|
| 336 |
+
entry = entry.copy()
|
| 337 |
+
entry["name"] = self._relpath(entry["name"])
|
| 338 |
+
out.append(entry)
|
| 339 |
+
return out
|
| 340 |
+
|
| 341 |
+
return self._relpath(ret)
|
| 342 |
+
|
| 343 |
+
def ls(self, path, detail=True, **kwargs):
|
| 344 |
+
ret = self.fs.ls(self._join(path), detail=detail, **kwargs).copy()
|
| 345 |
+
if detail:
|
| 346 |
+
out = []
|
| 347 |
+
for entry in ret:
|
| 348 |
+
entry = entry.copy()
|
| 349 |
+
entry["name"] = self._relpath(entry["name"])
|
| 350 |
+
out.append(entry)
|
| 351 |
+
return out
|
| 352 |
+
|
| 353 |
+
return self._relpath(ret)
|
| 354 |
+
|
| 355 |
+
def _relpath_walk_entries(self, entries):
|
| 356 |
+
# with detail=True, walk gives dicts keyed by basename whose infos
|
| 357 |
+
# still carry the full name in the wrapped filesystem
|
| 358 |
+
if not isinstance(entries, dict):
|
| 359 |
+
return entries
|
| 360 |
+
# Keep the mapping so callers can prune the wrapped walk in place.
|
| 361 |
+
for name, info in entries.items():
|
| 362 |
+
entries[name] = {**info, "name": self._relpath(info["name"])}
|
| 363 |
+
return entries
|
| 364 |
+
|
| 365 |
+
async def _walk(self, path, *args, **kwargs):
|
| 366 |
+
async for root, dirs, files in self.fs._walk(self._join(path), *args, **kwargs):
|
| 367 |
+
yield (
|
| 368 |
+
self._relpath(root),
|
| 369 |
+
self._relpath_walk_entries(dirs),
|
| 370 |
+
self._relpath_walk_entries(files),
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
def walk(self, path, *args, **kwargs):
|
| 374 |
+
for root, dirs, files in self.fs.walk(self._join(path), *args, **kwargs):
|
| 375 |
+
yield (
|
| 376 |
+
self._relpath(root),
|
| 377 |
+
self._relpath_walk_entries(dirs),
|
| 378 |
+
self._relpath_walk_entries(files),
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
async def _glob(self, path, **kwargs):
|
| 382 |
+
detail = kwargs.get("detail", False)
|
| 383 |
+
ret = await self.fs._glob(self._join(path), **kwargs)
|
| 384 |
+
if detail:
|
| 385 |
+
return self._relpath_detail(ret)
|
| 386 |
+
return self._relpath(ret)
|
| 387 |
+
|
| 388 |
+
def glob(self, path, **kwargs):
|
| 389 |
+
detail = kwargs.get("detail", False)
|
| 390 |
+
ret = self.fs.glob(self._join(path), **kwargs)
|
| 391 |
+
if detail:
|
| 392 |
+
return self._relpath_detail(ret)
|
| 393 |
+
return self._relpath(ret)
|
| 394 |
+
|
| 395 |
+
async def _du(self, path, *args, **kwargs):
|
| 396 |
+
total = kwargs.get("total", True)
|
| 397 |
+
ret = await self.fs._du(self._join(path), *args, **kwargs)
|
| 398 |
+
if total:
|
| 399 |
+
return ret
|
| 400 |
+
|
| 401 |
+
return {self._relpath(path): size for path, size in ret.items()}
|
| 402 |
+
|
| 403 |
+
def du(self, path, *args, **kwargs):
|
| 404 |
+
total = kwargs.get("total", True)
|
| 405 |
+
ret = self.fs.du(self._join(path), *args, **kwargs)
|
| 406 |
+
if total:
|
| 407 |
+
return ret
|
| 408 |
+
|
| 409 |
+
return {self._relpath(path): size for path, size in ret.items()}
|
| 410 |
+
|
| 411 |
+
async def _find(self, path, *args, **kwargs):
|
| 412 |
+
detail = kwargs.get("detail", False)
|
| 413 |
+
ret = await self.fs._find(self._join(path), *args, **kwargs)
|
| 414 |
+
if detail:
|
| 415 |
+
return self._relpath_detail(ret)
|
| 416 |
+
return self._relpath(ret)
|
| 417 |
+
|
| 418 |
+
def find(self, path, *args, **kwargs):
|
| 419 |
+
detail = kwargs.get("detail", False)
|
| 420 |
+
ret = self.fs.find(self._join(path), *args, **kwargs)
|
| 421 |
+
if detail:
|
| 422 |
+
return self._relpath_detail(ret)
|
| 423 |
+
return self._relpath(ret)
|
| 424 |
+
|
| 425 |
+
async def _expand_path(self, path, *args, **kwargs):
|
| 426 |
+
return self._relpath(
|
| 427 |
+
await self.fs._expand_path(self._join(path), *args, **kwargs)
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
def expand_path(self, path, *args, **kwargs):
|
| 431 |
+
return self._relpath(self.fs.expand_path(self._join(path), *args, **kwargs))
|
| 432 |
+
|
| 433 |
+
async def _mkdir(self, path, *args, **kwargs):
|
| 434 |
+
return await self.fs._mkdir(self._join(path), *args, **kwargs)
|
| 435 |
+
|
| 436 |
+
def mkdir(self, path, *args, **kwargs):
|
| 437 |
+
return self.fs.mkdir(self._join(path), *args, **kwargs)
|
| 438 |
+
|
| 439 |
+
async def _makedirs(self, path, *args, **kwargs):
|
| 440 |
+
return await self.fs._makedirs(self._join(path), *args, **kwargs)
|
| 441 |
+
|
| 442 |
+
def makedirs(self, path, *args, **kwargs):
|
| 443 |
+
return self.fs.makedirs(self._join(path), *args, **kwargs)
|
| 444 |
+
|
| 445 |
+
def rmdir(self, path):
|
| 446 |
+
return self.fs.rmdir(self._join(path))
|
| 447 |
+
|
| 448 |
+
def mv(self, path1, path2, **kwargs):
|
| 449 |
+
return self.fs.mv(
|
| 450 |
+
self._join(path1),
|
| 451 |
+
self._join(path2),
|
| 452 |
+
**kwargs,
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
def touch(self, path, **kwargs):
|
| 456 |
+
return self.fs.touch(self._join(path), **kwargs)
|
| 457 |
+
|
| 458 |
+
def created(self, path):
|
| 459 |
+
return self.fs.created(self._join(path))
|
| 460 |
+
|
| 461 |
+
def modified(self, path):
|
| 462 |
+
return self.fs.modified(self._join(path))
|
| 463 |
+
|
| 464 |
+
def sign(self, path, *args, **kwargs):
|
| 465 |
+
return self.fs.sign(self._join(path), *args, **kwargs)
|
| 466 |
+
|
| 467 |
+
def __repr__(self):
|
| 468 |
+
return f"{self.__class__.__qualname__}(path='{self.path}', fs={self.fs})"
|
| 469 |
+
|
| 470 |
+
def open(
|
| 471 |
+
self,
|
| 472 |
+
path,
|
| 473 |
+
*args,
|
| 474 |
+
**kwargs,
|
| 475 |
+
):
|
| 476 |
+
return self.fs.open(
|
| 477 |
+
self._join(path),
|
| 478 |
+
*args,
|
| 479 |
+
**kwargs,
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
async def open_async(
|
| 483 |
+
self,
|
| 484 |
+
path,
|
| 485 |
+
*args,
|
| 486 |
+
**kwargs,
|
| 487 |
+
):
|
| 488 |
+
return await self.fs.open_async(
|
| 489 |
+
self._join(path),
|
| 490 |
+
*args,
|
| 491 |
+
**kwargs,
|
| 492 |
+
)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/ftp.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import ssl
|
| 3 |
+
import uuid
|
| 4 |
+
from ftplib import FTP, FTP_TLS, Error, error_perm
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from ..spec import AbstractBufferedFile, AbstractFileSystem
|
| 8 |
+
from ..utils import infer_storage_options, isfilelike
|
| 9 |
+
|
| 10 |
+
SECURITY_PROTOCOL_MAP = {
|
| 11 |
+
"tls": ssl.PROTOCOL_TLS,
|
| 12 |
+
"sslv23": ssl.PROTOCOL_SSLv23,
|
| 13 |
+
}
|
| 14 |
+
for protocol in ["TLSv1", "TLSv1_1", "TLSv1_2"]:
|
| 15 |
+
if hasattr(ssl, f"PROTOCOL_{protocol}"):
|
| 16 |
+
SECURITY_PROTOCOL_MAP[protocol.lower()] = getattr(ssl, f"PROTOCOL_{protocol}")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ImplicitFTPTLS(FTP_TLS):
|
| 20 |
+
"""
|
| 21 |
+
FTP_TLS subclass that automatically wraps sockets in SSL
|
| 22 |
+
to support implicit FTPS.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, *args, **kwargs):
|
| 26 |
+
super().__init__(*args, **kwargs)
|
| 27 |
+
self._sock = None
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def sock(self):
|
| 31 |
+
"""Return the socket."""
|
| 32 |
+
return self._sock
|
| 33 |
+
|
| 34 |
+
@sock.setter
|
| 35 |
+
def sock(self, value):
|
| 36 |
+
"""When modifying the socket, ensure that it is ssl wrapped."""
|
| 37 |
+
if value is not None and not isinstance(value, ssl.SSLSocket):
|
| 38 |
+
value = self.context.wrap_socket(value)
|
| 39 |
+
self._sock = value
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class FTPFileSystem(AbstractFileSystem):
|
| 43 |
+
"""A filesystem over classic FTP"""
|
| 44 |
+
|
| 45 |
+
root_marker = "/"
|
| 46 |
+
cachable = False
|
| 47 |
+
protocol = "ftp"
|
| 48 |
+
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
host,
|
| 52 |
+
port=21,
|
| 53 |
+
username=None,
|
| 54 |
+
password=None,
|
| 55 |
+
acct=None,
|
| 56 |
+
block_size=None,
|
| 57 |
+
tempdir=None,
|
| 58 |
+
timeout=30,
|
| 59 |
+
encoding="utf-8",
|
| 60 |
+
tls=False,
|
| 61 |
+
**kwargs,
|
| 62 |
+
):
|
| 63 |
+
"""
|
| 64 |
+
You can use _get_kwargs_from_urls to get some kwargs from
|
| 65 |
+
a reasonable FTP url.
|
| 66 |
+
|
| 67 |
+
Authentication will be anonymous if username/password are not
|
| 68 |
+
given.
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
host: str
|
| 73 |
+
The remote server name/ip to connect to
|
| 74 |
+
port: int
|
| 75 |
+
Port to connect with
|
| 76 |
+
username: str or None
|
| 77 |
+
If authenticating, the user's identifier
|
| 78 |
+
password: str of None
|
| 79 |
+
User's password on the server, if using
|
| 80 |
+
acct: str or None
|
| 81 |
+
Some servers also need an "account" string for auth
|
| 82 |
+
block_size: int or None
|
| 83 |
+
If given, the read-ahead or write buffer size.
|
| 84 |
+
tempdir: str
|
| 85 |
+
Directory on remote to put temporary files when in a transaction
|
| 86 |
+
timeout: int
|
| 87 |
+
Timeout of the ftp connection in seconds
|
| 88 |
+
encoding: str
|
| 89 |
+
Encoding to use for directories and filenames in FTP connection
|
| 90 |
+
tls: bool or str
|
| 91 |
+
Enable FTP-TLS for secure connections:
|
| 92 |
+
- False: Plain FTP (default)
|
| 93 |
+
- True: Explicit TLS (FTPS with AUTH TLS command)
|
| 94 |
+
- "tls": Auto-negotiate highest protocol
|
| 95 |
+
- "tlsv1": TLS v1.0
|
| 96 |
+
- "tlsv1_1": TLS v1.1
|
| 97 |
+
- "tlsv1_2": TLS v1.2
|
| 98 |
+
"""
|
| 99 |
+
super().__init__(**kwargs)
|
| 100 |
+
self.host = host
|
| 101 |
+
self.port = port
|
| 102 |
+
self.tempdir = tempdir or "/tmp"
|
| 103 |
+
self.cred = username or "", password or "", acct or ""
|
| 104 |
+
self.timeout = timeout
|
| 105 |
+
self.encoding = encoding
|
| 106 |
+
if block_size is not None:
|
| 107 |
+
self.blocksize = block_size
|
| 108 |
+
else:
|
| 109 |
+
self.blocksize = 2**16
|
| 110 |
+
self.tls = tls
|
| 111 |
+
self._connect()
|
| 112 |
+
|
| 113 |
+
def _connect(self):
|
| 114 |
+
security = None
|
| 115 |
+
if self.tls:
|
| 116 |
+
if isinstance(self.tls, str):
|
| 117 |
+
ftp_cls = ImplicitFTPTLS
|
| 118 |
+
security = SECURITY_PROTOCOL_MAP.get(
|
| 119 |
+
self.tls,
|
| 120 |
+
f"Not supported {self.tls} protocol",
|
| 121 |
+
)
|
| 122 |
+
if isinstance(security, str):
|
| 123 |
+
raise ValueError(security)
|
| 124 |
+
else:
|
| 125 |
+
ftp_cls = FTP_TLS
|
| 126 |
+
else:
|
| 127 |
+
ftp_cls = FTP
|
| 128 |
+
self.ftp = ftp_cls(timeout=self.timeout, encoding=self.encoding)
|
| 129 |
+
if security:
|
| 130 |
+
self.ftp.ssl_version = security
|
| 131 |
+
self.ftp.connect(self.host, self.port)
|
| 132 |
+
self.ftp.login(*self.cred)
|
| 133 |
+
if isinstance(self.tls, bool) and self.tls:
|
| 134 |
+
# also on a reconnect, which would otherwise send data in clear
|
| 135 |
+
self.ftp.prot_p()
|
| 136 |
+
|
| 137 |
+
@classmethod
|
| 138 |
+
def _strip_protocol(cls, path):
|
| 139 |
+
return "/" + infer_storage_options(path)["path"].lstrip("/").rstrip("/")
|
| 140 |
+
|
| 141 |
+
@staticmethod
|
| 142 |
+
def _get_kwargs_from_urls(urlpath):
|
| 143 |
+
out = infer_storage_options(urlpath)
|
| 144 |
+
out.pop("path", None)
|
| 145 |
+
out.pop("protocol", None)
|
| 146 |
+
return out
|
| 147 |
+
|
| 148 |
+
def ls(self, path, detail=True, **kwargs):
|
| 149 |
+
path = self._strip_protocol(path)
|
| 150 |
+
out = []
|
| 151 |
+
if path not in self.dircache:
|
| 152 |
+
try:
|
| 153 |
+
try:
|
| 154 |
+
out = [
|
| 155 |
+
(fn, details)
|
| 156 |
+
for (fn, details) in self.ftp.mlsd(path)
|
| 157 |
+
if fn not in [".", ".."]
|
| 158 |
+
and details["type"] not in ["pdir", "cdir"]
|
| 159 |
+
]
|
| 160 |
+
except error_perm:
|
| 161 |
+
out = _mlsd2(self.ftp, path) # Not platform independent
|
| 162 |
+
for fn, details in out:
|
| 163 |
+
details["name"] = "/".join(
|
| 164 |
+
["" if path == "/" else path, fn.lstrip("/")]
|
| 165 |
+
)
|
| 166 |
+
if details["type"] == "file":
|
| 167 |
+
details["size"] = int(details["size"])
|
| 168 |
+
else:
|
| 169 |
+
details["size"] = 0
|
| 170 |
+
if details["type"] == "dir":
|
| 171 |
+
details["type"] = "directory"
|
| 172 |
+
self.dircache[path] = out
|
| 173 |
+
except Error:
|
| 174 |
+
try:
|
| 175 |
+
info = self.info(path)
|
| 176 |
+
if info["type"] == "file":
|
| 177 |
+
out = [(path, info)]
|
| 178 |
+
except (Error, IndexError) as exc:
|
| 179 |
+
raise FileNotFoundError(path) from exc
|
| 180 |
+
files = self.dircache.get(path, out)
|
| 181 |
+
if not detail:
|
| 182 |
+
return sorted([fn for fn, details in files])
|
| 183 |
+
return [details for fn, details in files]
|
| 184 |
+
|
| 185 |
+
def info(self, path, **kwargs):
|
| 186 |
+
# implement with direct method
|
| 187 |
+
path = self._strip_protocol(path)
|
| 188 |
+
if path == "/":
|
| 189 |
+
# special case, since this dir has no real entry
|
| 190 |
+
return {"name": "/", "size": 0, "type": "directory"}
|
| 191 |
+
files = self.ls(self._parent(path).lstrip("/"), True)
|
| 192 |
+
try:
|
| 193 |
+
out = next(f for f in files if f["name"] == path)
|
| 194 |
+
except StopIteration as exc:
|
| 195 |
+
raise FileNotFoundError(path) from exc
|
| 196 |
+
return out
|
| 197 |
+
|
| 198 |
+
def get_file(self, rpath, lpath, **kwargs):
|
| 199 |
+
rpath = self._strip_protocol(rpath)
|
| 200 |
+
if self.isdir(rpath):
|
| 201 |
+
if not os.path.exists(lpath):
|
| 202 |
+
os.mkdir(lpath)
|
| 203 |
+
return
|
| 204 |
+
if isfilelike(lpath):
|
| 205 |
+
outfile = lpath
|
| 206 |
+
else:
|
| 207 |
+
outfile = open(lpath, "wb")
|
| 208 |
+
|
| 209 |
+
def cb(x):
|
| 210 |
+
outfile.write(x)
|
| 211 |
+
|
| 212 |
+
self.ftp.retrbinary(
|
| 213 |
+
f"RETR {rpath}",
|
| 214 |
+
blocksize=self.blocksize,
|
| 215 |
+
callback=cb,
|
| 216 |
+
)
|
| 217 |
+
if not isfilelike(lpath):
|
| 218 |
+
outfile.close()
|
| 219 |
+
|
| 220 |
+
def cat_file(self, path, start=None, end=None, **kwargs):
|
| 221 |
+
path = self._strip_protocol(path)
|
| 222 |
+
if end is not None or (start is not None and start < 0):
|
| 223 |
+
return super().cat_file(path, start, end, **kwargs)
|
| 224 |
+
out = []
|
| 225 |
+
|
| 226 |
+
def cb(x):
|
| 227 |
+
out.append(x)
|
| 228 |
+
|
| 229 |
+
try:
|
| 230 |
+
self.ftp.retrbinary(
|
| 231 |
+
f"RETR {path}",
|
| 232 |
+
blocksize=self.blocksize,
|
| 233 |
+
rest=start,
|
| 234 |
+
callback=cb,
|
| 235 |
+
)
|
| 236 |
+
except (Error, error_perm) as orig_exc:
|
| 237 |
+
raise FileNotFoundError(path) from orig_exc
|
| 238 |
+
return b"".join(out)
|
| 239 |
+
|
| 240 |
+
def _open(
|
| 241 |
+
self,
|
| 242 |
+
path,
|
| 243 |
+
mode="rb",
|
| 244 |
+
block_size=None,
|
| 245 |
+
cache_options=None,
|
| 246 |
+
autocommit=True,
|
| 247 |
+
**kwargs,
|
| 248 |
+
):
|
| 249 |
+
path = self._strip_protocol(path)
|
| 250 |
+
block_size = block_size or self.blocksize
|
| 251 |
+
return FTPFile(
|
| 252 |
+
self,
|
| 253 |
+
path,
|
| 254 |
+
mode=mode,
|
| 255 |
+
block_size=block_size,
|
| 256 |
+
tempdir=self.tempdir,
|
| 257 |
+
autocommit=autocommit,
|
| 258 |
+
cache_options=cache_options,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
def _rm(self, path):
|
| 262 |
+
path = self._strip_protocol(path)
|
| 263 |
+
self.ftp.delete(path)
|
| 264 |
+
self.invalidate_cache(self._parent(path))
|
| 265 |
+
|
| 266 |
+
def rm(self, path, recursive=False, maxdepth=None):
|
| 267 |
+
paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
|
| 268 |
+
for p in reversed(paths):
|
| 269 |
+
if self.isfile(p):
|
| 270 |
+
self.rm_file(p)
|
| 271 |
+
else:
|
| 272 |
+
self.rmdir(p)
|
| 273 |
+
|
| 274 |
+
def mkdir(self, path: str, create_parents: bool = True, **kwargs: Any) -> None:
|
| 275 |
+
path = self._strip_protocol(path)
|
| 276 |
+
parent = self._parent(path)
|
| 277 |
+
if parent != self.root_marker and not self.exists(parent) and create_parents:
|
| 278 |
+
self.mkdir(parent, create_parents=create_parents)
|
| 279 |
+
|
| 280 |
+
self.ftp.mkd(path)
|
| 281 |
+
self.invalidate_cache(self._parent(path))
|
| 282 |
+
|
| 283 |
+
def makedirs(self, path: str, exist_ok: bool = False) -> None:
|
| 284 |
+
path = self._strip_protocol(path)
|
| 285 |
+
if self.exists(path):
|
| 286 |
+
# NB: "/" does not "exist" as it has no directory entry
|
| 287 |
+
if not exist_ok:
|
| 288 |
+
raise FileExistsError(f"{path} exists without `exist_ok`")
|
| 289 |
+
# exists_ok=True -> no-op
|
| 290 |
+
else:
|
| 291 |
+
self.mkdir(path, create_parents=True)
|
| 292 |
+
|
| 293 |
+
def rmdir(self, path):
|
| 294 |
+
path = self._strip_protocol(path)
|
| 295 |
+
self.ftp.rmd(path)
|
| 296 |
+
self.invalidate_cache(self._parent(path))
|
| 297 |
+
|
| 298 |
+
def mv(self, path1, path2, **kwargs):
|
| 299 |
+
path1 = self._strip_protocol(path1)
|
| 300 |
+
path2 = self._strip_protocol(path2)
|
| 301 |
+
self.ftp.rename(path1, path2)
|
| 302 |
+
self.invalidate_cache(self._parent(path1))
|
| 303 |
+
self.invalidate_cache(self._parent(path2))
|
| 304 |
+
|
| 305 |
+
def __del__(self):
|
| 306 |
+
self.ftp.close()
|
| 307 |
+
|
| 308 |
+
def invalidate_cache(self, path=None):
|
| 309 |
+
if path is None:
|
| 310 |
+
self.dircache.clear()
|
| 311 |
+
else:
|
| 312 |
+
self.dircache.pop(path, None)
|
| 313 |
+
super().invalidate_cache(path)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class TransferDone(Exception):
|
| 317 |
+
"""Internal exception to break out of transfer"""
|
| 318 |
+
|
| 319 |
+
pass
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class FTPFile(AbstractBufferedFile):
|
| 323 |
+
"""Interact with a remote FTP file with read/write buffering"""
|
| 324 |
+
|
| 325 |
+
def __init__(
|
| 326 |
+
self,
|
| 327 |
+
fs,
|
| 328 |
+
path,
|
| 329 |
+
mode="rb",
|
| 330 |
+
block_size="default",
|
| 331 |
+
autocommit=True,
|
| 332 |
+
cache_type="readahead",
|
| 333 |
+
cache_options=None,
|
| 334 |
+
**kwargs,
|
| 335 |
+
):
|
| 336 |
+
super().__init__(
|
| 337 |
+
fs,
|
| 338 |
+
path,
|
| 339 |
+
mode=mode,
|
| 340 |
+
block_size=block_size,
|
| 341 |
+
autocommit=autocommit,
|
| 342 |
+
cache_type=cache_type,
|
| 343 |
+
cache_options=cache_options,
|
| 344 |
+
**kwargs,
|
| 345 |
+
)
|
| 346 |
+
if not autocommit:
|
| 347 |
+
self.target = self.path
|
| 348 |
+
self.path = "/".join([kwargs["tempdir"], str(uuid.uuid4())])
|
| 349 |
+
|
| 350 |
+
def commit(self):
|
| 351 |
+
self.fs.mv(self.path, self.target)
|
| 352 |
+
|
| 353 |
+
def discard(self):
|
| 354 |
+
self.fs.rm(self.path)
|
| 355 |
+
|
| 356 |
+
def _fetch_range(self, start, end):
|
| 357 |
+
"""Get bytes between given byte limits
|
| 358 |
+
|
| 359 |
+
Implemented by raising an exception in the fetch callback when the
|
| 360 |
+
number of bytes received reaches the requested amount.
|
| 361 |
+
|
| 362 |
+
Will fail if the server does not respect the REST command on
|
| 363 |
+
retrieve requests.
|
| 364 |
+
"""
|
| 365 |
+
out = []
|
| 366 |
+
total = [0]
|
| 367 |
+
|
| 368 |
+
def callback(x):
|
| 369 |
+
total[0] += len(x)
|
| 370 |
+
if total[0] > end - start:
|
| 371 |
+
out.append(x[: (end - start) - total[0]])
|
| 372 |
+
if end < self.size:
|
| 373 |
+
raise TransferDone
|
| 374 |
+
else:
|
| 375 |
+
out.append(x)
|
| 376 |
+
|
| 377 |
+
if total[0] == end - start and end < self.size:
|
| 378 |
+
raise TransferDone
|
| 379 |
+
|
| 380 |
+
try:
|
| 381 |
+
self.fs.ftp.retrbinary(
|
| 382 |
+
f"RETR {self.path}",
|
| 383 |
+
blocksize=self.blocksize,
|
| 384 |
+
rest=start,
|
| 385 |
+
callback=callback,
|
| 386 |
+
)
|
| 387 |
+
except TransferDone:
|
| 388 |
+
try:
|
| 389 |
+
# stop transfer, we got enough bytes for this block
|
| 390 |
+
self.fs.ftp.abort()
|
| 391 |
+
self.fs.ftp.getmultiline()
|
| 392 |
+
except Error:
|
| 393 |
+
self.fs._connect()
|
| 394 |
+
|
| 395 |
+
return b"".join(out)
|
| 396 |
+
|
| 397 |
+
def _upload_chunk(self, final=False):
|
| 398 |
+
self.buffer.seek(0)
|
| 399 |
+
self.fs.ftp.storbinary(
|
| 400 |
+
f"STOR {self.path}", self.buffer, blocksize=self.blocksize, rest=self.offset
|
| 401 |
+
)
|
| 402 |
+
return True
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def _mlsd2(ftp, path="."):
|
| 406 |
+
"""
|
| 407 |
+
Fall back to using `dir` instead of `mlsd` if not supported.
|
| 408 |
+
|
| 409 |
+
This parses a Linux style `ls -l` response to `dir`, but the response may
|
| 410 |
+
be platform dependent.
|
| 411 |
+
|
| 412 |
+
Parameters
|
| 413 |
+
----------
|
| 414 |
+
ftp: ftplib.FTP
|
| 415 |
+
path: str
|
| 416 |
+
Expects to be given path, but defaults to ".".
|
| 417 |
+
"""
|
| 418 |
+
lines = []
|
| 419 |
+
minfo = []
|
| 420 |
+
ftp.dir(path, lines.append)
|
| 421 |
+
for line in lines:
|
| 422 |
+
split_line = line.split(maxsplit=8)
|
| 423 |
+
if len(split_line) < 9:
|
| 424 |
+
continue
|
| 425 |
+
name = split_line[8]
|
| 426 |
+
unix_mode = split_line[0]
|
| 427 |
+
if unix_mode[0] == "l" and " -> " in name:
|
| 428 |
+
# Symbolic link: "<name> -> <target>"; keep only the link name.
|
| 429 |
+
name = name.split(" -> ", 1)[0]
|
| 430 |
+
this = (
|
| 431 |
+
name,
|
| 432 |
+
{
|
| 433 |
+
"modify": " ".join(split_line[5:8]),
|
| 434 |
+
"unix.owner": split_line[2],
|
| 435 |
+
"unix.group": split_line[3],
|
| 436 |
+
"unix.mode": unix_mode,
|
| 437 |
+
"size": split_line[4],
|
| 438 |
+
},
|
| 439 |
+
)
|
| 440 |
+
if this[1]["unix.mode"][0] == "d":
|
| 441 |
+
this[1]["type"] = "dir"
|
| 442 |
+
else:
|
| 443 |
+
this[1]["type"] = "file"
|
| 444 |
+
minfo.append(this)
|
| 445 |
+
return minfo
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/gist.py
ADDED
|
@@ -0,0 +1,241 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/git.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
For example, "git://C:/repo:master@file" selects a branch in
|
| 31 |
+
a Windows repository, and "git://C:/repo:file" uses the default ref.
|
| 32 |
+
fo: str (optional)
|
| 33 |
+
Same as ``path``, but passed as part of a chained URL. This one
|
| 34 |
+
takes precedence if both are given.
|
| 35 |
+
ref: str (optional)
|
| 36 |
+
Reference to work with, could be a hash, tag or branch name. Defaults
|
| 37 |
+
to current working tree. Note that ``ls`` and ``open`` also take hash,
|
| 38 |
+
so this becomes the default for those operations
|
| 39 |
+
kwargs
|
| 40 |
+
"""
|
| 41 |
+
super().__init__(**kwargs)
|
| 42 |
+
self.repo = pygit2.Repository(fo or path or os.getcwd())
|
| 43 |
+
self.ref = ref or "master"
|
| 44 |
+
|
| 45 |
+
@classmethod
|
| 46 |
+
def _strip_protocol(cls, path):
|
| 47 |
+
path = super()._strip_protocol(path).lstrip("/")
|
| 48 |
+
if ":" in path:
|
| 49 |
+
path = path.rsplit(":", 1)[1]
|
| 50 |
+
if "@" in path:
|
| 51 |
+
path = path.split("@", 1)[1]
|
| 52 |
+
return path.lstrip("/")
|
| 53 |
+
|
| 54 |
+
def _path_to_object(self, path, ref):
|
| 55 |
+
comm, ref = self.repo.resolve_refish(ref or self.ref)
|
| 56 |
+
parts = path.split("/")
|
| 57 |
+
tree = comm.tree
|
| 58 |
+
for part in parts:
|
| 59 |
+
if not part:
|
| 60 |
+
continue
|
| 61 |
+
if not isinstance(tree, pygit2.Tree) or part not in tree:
|
| 62 |
+
raise FileNotFoundError(path)
|
| 63 |
+
tree = tree[part]
|
| 64 |
+
return tree
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def _get_kwargs_from_urls(path):
|
| 68 |
+
path = path.removeprefix("git://")
|
| 69 |
+
out = {}
|
| 70 |
+
if ":" in path:
|
| 71 |
+
out["path"], path = path.rsplit(":", 1)
|
| 72 |
+
if "@" in path:
|
| 73 |
+
out["ref"], path = path.split("@", 1)
|
| 74 |
+
return out
|
| 75 |
+
|
| 76 |
+
@staticmethod
|
| 77 |
+
def _object_to_info(obj, path=None):
|
| 78 |
+
# obj.name and obj.filemode are None for the root tree!
|
| 79 |
+
is_dir = isinstance(obj, pygit2.Tree)
|
| 80 |
+
return {
|
| 81 |
+
"type": "directory" if is_dir else "file",
|
| 82 |
+
"name": (
|
| 83 |
+
"/".join([path, obj.name or ""]).lstrip("/") if path else obj.name
|
| 84 |
+
),
|
| 85 |
+
"hex": str(obj.id),
|
| 86 |
+
"mode": "100644" if obj.filemode is None else f"{obj.filemode:o}",
|
| 87 |
+
"size": 0 if is_dir else obj.size,
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
def ls(self, path, detail=True, ref=None, **kwargs):
|
| 91 |
+
path = self._strip_protocol(path).rstrip("/")
|
| 92 |
+
tree = self._path_to_object(path, ref)
|
| 93 |
+
if not isinstance(tree, pygit2.Tree):
|
| 94 |
+
return [self.info(path, ref=ref)] if detail else [path]
|
| 95 |
+
return [
|
| 96 |
+
GitFileSystem._object_to_info(obj, path)
|
| 97 |
+
if detail
|
| 98 |
+
else GitFileSystem._object_to_info(obj, path)["name"]
|
| 99 |
+
for obj in tree
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
def info(self, path, ref=None, **kwargs):
|
| 103 |
+
path = self._strip_protocol(path).rstrip("/")
|
| 104 |
+
tree = self._path_to_object(path, ref)
|
| 105 |
+
info = GitFileSystem._object_to_info(tree)
|
| 106 |
+
info["name"] = path
|
| 107 |
+
return info
|
| 108 |
+
|
| 109 |
+
def ukey(self, path, ref=None):
|
| 110 |
+
return self.info(path, ref=ref)["hex"]
|
| 111 |
+
|
| 112 |
+
def _open(
|
| 113 |
+
self,
|
| 114 |
+
path,
|
| 115 |
+
mode="rb",
|
| 116 |
+
block_size=None,
|
| 117 |
+
autocommit=True,
|
| 118 |
+
cache_options=None,
|
| 119 |
+
ref=None,
|
| 120 |
+
**kwargs,
|
| 121 |
+
):
|
| 122 |
+
obj = self._path_to_object(path, ref or self.ref)
|
| 123 |
+
return MemoryFile(data=obj.data)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/github.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import re
|
| 3 |
+
from urllib.parse import quote
|
| 4 |
+
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
from ..spec import AbstractFileSystem
|
| 8 |
+
from ..utils import infer_storage_options
|
| 9 |
+
from .memory import MemoryFile
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _github_names(url, timeout, **kwargs):
|
| 13 |
+
names = []
|
| 14 |
+
while url:
|
| 15 |
+
response = requests.get(url, timeout=timeout, **kwargs)
|
| 16 |
+
response.raise_for_status()
|
| 17 |
+
names.extend(item["name"] for item in response.json())
|
| 18 |
+
url = response.links.get("next", {}).get("url")
|
| 19 |
+
return names
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class GithubFileSystem(AbstractFileSystem):
|
| 23 |
+
"""Interface to files in github
|
| 24 |
+
|
| 25 |
+
An instance of this class provides the files residing within a remote github
|
| 26 |
+
repository. You may specify a point in the repos history, by SHA, branch
|
| 27 |
+
or tag (default is current master).
|
| 28 |
+
|
| 29 |
+
For files less than 1 MB in size, file content is returned directly in a
|
| 30 |
+
MemoryFile. For larger files, or for files tracked by git-lfs, file content
|
| 31 |
+
is returned as an HTTPFile wrapping the ``download_url`` provided by the
|
| 32 |
+
GitHub API.
|
| 33 |
+
|
| 34 |
+
When using fsspec.open, allows URIs of the form:
|
| 35 |
+
|
| 36 |
+
- "github://path/file", in which case you must specify org, repo and
|
| 37 |
+
may specify sha in the extra args
|
| 38 |
+
- 'github://org:repo@/precip/catalog.yml', where the org and repo are
|
| 39 |
+
part of the URI
|
| 40 |
+
- 'github://org:repo@sha/precip/catalog.yml', where the sha is also included
|
| 41 |
+
|
| 42 |
+
``sha`` can be the full or abbreviated hex of the commit you want to fetch
|
| 43 |
+
from, or a branch or tag name. Pass the unencoded name in the ``sha`` option;
|
| 44 |
+
it is percent-encoded when constructing GitHub API URLs.
|
| 45 |
+
|
| 46 |
+
For authorised access, you must provide username and token, which can be made
|
| 47 |
+
at https://github.com/settings/tokens
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
url = "https://api.github.com/repos/{org}/{repo}/git/trees/{sha}"
|
| 51 |
+
content_url = "https://api.github.com/repos/{org}/{repo}/contents/{path}?ref={sha}"
|
| 52 |
+
protocol = "github"
|
| 53 |
+
timeout = (60, 60) # connect, read timeouts
|
| 54 |
+
|
| 55 |
+
def __init__(
|
| 56 |
+
self, org, repo, sha=None, username=None, token=None, timeout=None, **kwargs
|
| 57 |
+
):
|
| 58 |
+
super().__init__(**kwargs)
|
| 59 |
+
self.org = org
|
| 60 |
+
self.repo = repo
|
| 61 |
+
if (username is None) ^ (token is None):
|
| 62 |
+
raise ValueError("Auth required both username and token")
|
| 63 |
+
self.username = username
|
| 64 |
+
self.token = token
|
| 65 |
+
if timeout is not None:
|
| 66 |
+
self.timeout = timeout
|
| 67 |
+
if sha is None:
|
| 68 |
+
# look up default branch (not necessarily "master")
|
| 69 |
+
u = "https://api.github.com/repos/{org}/{repo}"
|
| 70 |
+
r = requests.get(
|
| 71 |
+
u.format(org=org, repo=repo), timeout=self.timeout, **self.kw
|
| 72 |
+
)
|
| 73 |
+
r.raise_for_status()
|
| 74 |
+
sha = r.json()["default_branch"]
|
| 75 |
+
|
| 76 |
+
self.root = sha
|
| 77 |
+
self.ls("")
|
| 78 |
+
try:
|
| 79 |
+
from .http import HTTPFileSystem
|
| 80 |
+
|
| 81 |
+
self.http_fs = HTTPFileSystem(**kwargs)
|
| 82 |
+
except ImportError:
|
| 83 |
+
self.http_fs = None
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def kw(self):
|
| 87 |
+
if self.username:
|
| 88 |
+
return {"auth": (self.username, self.token)}
|
| 89 |
+
return {}
|
| 90 |
+
|
| 91 |
+
@classmethod
|
| 92 |
+
def repos(cls, org_or_user, is_org=True):
|
| 93 |
+
"""List repo names for given org or user
|
| 94 |
+
|
| 95 |
+
This may become the top level of the FS
|
| 96 |
+
|
| 97 |
+
Parameters
|
| 98 |
+
----------
|
| 99 |
+
org_or_user: str
|
| 100 |
+
Name of the github org or user to query
|
| 101 |
+
is_org: bool (default True)
|
| 102 |
+
Whether the name is an organisation (True) or user (False)
|
| 103 |
+
|
| 104 |
+
Returns
|
| 105 |
+
-------
|
| 106 |
+
List of string
|
| 107 |
+
"""
|
| 108 |
+
return _github_names(
|
| 109 |
+
f"https://api.github.com/{['users', 'orgs'][is_org]}/{org_or_user}/repos",
|
| 110 |
+
timeout=cls.timeout,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def tags(self):
|
| 115 |
+
"""Names of tags in the repo"""
|
| 116 |
+
return _github_names(
|
| 117 |
+
f"https://api.github.com/repos/{self.org}/{self.repo}/tags",
|
| 118 |
+
timeout=self.timeout,
|
| 119 |
+
**self.kw,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
@property
|
| 123 |
+
def branches(self):
|
| 124 |
+
"""Names of branches in the repo"""
|
| 125 |
+
return _github_names(
|
| 126 |
+
f"https://api.github.com/repos/{self.org}/{self.repo}/branches",
|
| 127 |
+
timeout=self.timeout,
|
| 128 |
+
**self.kw,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
@property
|
| 132 |
+
def refs(self):
|
| 133 |
+
"""Named references, tags and branches"""
|
| 134 |
+
return {"tags": self.tags, "branches": self.branches}
|
| 135 |
+
|
| 136 |
+
def ls(self, path, detail=False, sha=None, _sha=None, **kwargs):
|
| 137 |
+
"""List files at given path
|
| 138 |
+
|
| 139 |
+
Parameters
|
| 140 |
+
----------
|
| 141 |
+
path: str
|
| 142 |
+
Location to list, relative to repo root
|
| 143 |
+
detail: bool
|
| 144 |
+
If True, returns list of dicts, one per file; if False, returns
|
| 145 |
+
list of full filenames only
|
| 146 |
+
sha: str (optional)
|
| 147 |
+
List at the given point in the repo history, branch or tag name or commit
|
| 148 |
+
SHA
|
| 149 |
+
_sha: str (optional)
|
| 150 |
+
List this specific tree object (used internally to descend into trees)
|
| 151 |
+
"""
|
| 152 |
+
path = self._strip_protocol(path)
|
| 153 |
+
if path == "":
|
| 154 |
+
_sha = sha or self.root
|
| 155 |
+
if _sha is None:
|
| 156 |
+
parts = path.rstrip("/").split("/")
|
| 157 |
+
so_far = ""
|
| 158 |
+
_sha = sha or self.root
|
| 159 |
+
for part in parts:
|
| 160 |
+
out = self.ls(so_far, True, sha=sha, _sha=_sha)
|
| 161 |
+
so_far += "/" + part if so_far else part
|
| 162 |
+
out = [o for o in out if o["name"] == so_far]
|
| 163 |
+
if not out:
|
| 164 |
+
raise FileNotFoundError(path)
|
| 165 |
+
out = out[0]
|
| 166 |
+
if out["type"] == "file":
|
| 167 |
+
if detail:
|
| 168 |
+
return [out]
|
| 169 |
+
else:
|
| 170 |
+
return [out["name"]]
|
| 171 |
+
_sha = out["sha"]
|
| 172 |
+
if path not in self.dircache or sha not in [self.root, None]:
|
| 173 |
+
r = requests.get(
|
| 174 |
+
self.url.format(org=self.org, repo=self.repo, sha=quote(_sha, safe="")),
|
| 175 |
+
timeout=self.timeout,
|
| 176 |
+
**self.kw,
|
| 177 |
+
)
|
| 178 |
+
if r.status_code == 404:
|
| 179 |
+
raise FileNotFoundError(path)
|
| 180 |
+
r.raise_for_status()
|
| 181 |
+
types = {"blob": "file", "tree": "directory"}
|
| 182 |
+
out = [
|
| 183 |
+
{
|
| 184 |
+
"name": path + "/" + f["path"] if path else f["path"],
|
| 185 |
+
"mode": f["mode"],
|
| 186 |
+
"type": types[f["type"]],
|
| 187 |
+
"size": f.get("size", 0),
|
| 188 |
+
"sha": f["sha"],
|
| 189 |
+
}
|
| 190 |
+
for f in r.json()["tree"]
|
| 191 |
+
if f["type"] in types
|
| 192 |
+
]
|
| 193 |
+
if sha in [self.root, None]:
|
| 194 |
+
self.dircache[path] = out
|
| 195 |
+
else:
|
| 196 |
+
out = self.dircache[path]
|
| 197 |
+
if detail:
|
| 198 |
+
return out
|
| 199 |
+
else:
|
| 200 |
+
return sorted([f["name"] for f in out])
|
| 201 |
+
|
| 202 |
+
def invalidate_cache(self, path=None):
|
| 203 |
+
self.dircache.clear()
|
| 204 |
+
|
| 205 |
+
@classmethod
|
| 206 |
+
def _strip_protocol(cls, path):
|
| 207 |
+
opts = infer_storage_options(path)
|
| 208 |
+
if "username" not in opts:
|
| 209 |
+
return super()._strip_protocol(path)
|
| 210 |
+
return opts["path"].lstrip("/")
|
| 211 |
+
|
| 212 |
+
@staticmethod
|
| 213 |
+
def _get_kwargs_from_urls(path):
|
| 214 |
+
opts = infer_storage_options(path)
|
| 215 |
+
if "username" not in opts:
|
| 216 |
+
return {}
|
| 217 |
+
out = {"org": opts["username"], "repo": opts["password"]}
|
| 218 |
+
if opts["host"]:
|
| 219 |
+
out["sha"] = opts["host"]
|
| 220 |
+
return out
|
| 221 |
+
|
| 222 |
+
def _open(
|
| 223 |
+
self,
|
| 224 |
+
path,
|
| 225 |
+
mode="rb",
|
| 226 |
+
block_size=None,
|
| 227 |
+
cache_options=None,
|
| 228 |
+
sha=None,
|
| 229 |
+
**kwargs,
|
| 230 |
+
):
|
| 231 |
+
if mode != "rb":
|
| 232 |
+
raise NotImplementedError
|
| 233 |
+
|
| 234 |
+
# construct a url to hit the GitHub API's repo contents API
|
| 235 |
+
url = self.content_url.format(
|
| 236 |
+
org=self.org,
|
| 237 |
+
repo=self.repo,
|
| 238 |
+
path=quote(path),
|
| 239 |
+
sha=quote(sha or self.root, safe=""),
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# make a request to this API, and parse the response as JSON
|
| 243 |
+
r = requests.get(url, timeout=self.timeout, **self.kw)
|
| 244 |
+
if r.status_code == 404:
|
| 245 |
+
raise FileNotFoundError(path)
|
| 246 |
+
r.raise_for_status()
|
| 247 |
+
content_json = r.json()
|
| 248 |
+
|
| 249 |
+
# Inline base64 content may be empty for a zero-byte file. Large files
|
| 250 |
+
# report encoding="none" and need the download fallback below.
|
| 251 |
+
if content_json.get("encoding") == "base64":
|
| 252 |
+
content = base64.b64decode(content_json["content"])
|
| 253 |
+
|
| 254 |
+
# as long as the content does not start with the string
|
| 255 |
+
# "version https://git-lfs.github.com/"
|
| 256 |
+
# then it is probably not a git-lfs pointer and we can just return
|
| 257 |
+
# the content directly
|
| 258 |
+
if not content.startswith(b"version https://git-lfs.github.com/"):
|
| 259 |
+
return MemoryFile(None, None, content)
|
| 260 |
+
|
| 261 |
+
# we land here if the content was not present in the first response
|
| 262 |
+
# (regular file over 1MB or git-lfs tracked file)
|
| 263 |
+
# in this case, we get let the HTTPFileSystem handle the download
|
| 264 |
+
if self.http_fs is None:
|
| 265 |
+
raise ImportError(
|
| 266 |
+
"Please install fsspec[http] to access github files >1 MB "
|
| 267 |
+
"or git-lfs tracked files."
|
| 268 |
+
)
|
| 269 |
+
return self.http_fs.open(
|
| 270 |
+
content_json["download_url"],
|
| 271 |
+
mode=mode,
|
| 272 |
+
block_size=block_size,
|
| 273 |
+
cache_options=cache_options,
|
| 274 |
+
**kwargs,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
def rm(self, path, recursive=False, maxdepth=None, message=None):
|
| 278 |
+
path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
|
| 279 |
+
for p in reversed(path):
|
| 280 |
+
self.rm_file(p, message=message)
|
| 281 |
+
|
| 282 |
+
def rm_file(self, path, message=None, **kwargs):
|
| 283 |
+
"""
|
| 284 |
+
Remove a file from a specified branch using a given commit message.
|
| 285 |
+
|
| 286 |
+
Since Github DELETE operation requires a branch name, and we can't reliably
|
| 287 |
+
determine whether the provided SHA refers to a branch, tag, or commit, we
|
| 288 |
+
assume it's a branch. If it's not, the user will encounter an error when
|
| 289 |
+
attempting to retrieve the file SHA or delete the file.
|
| 290 |
+
|
| 291 |
+
Parameters
|
| 292 |
+
----------
|
| 293 |
+
path: str
|
| 294 |
+
The file's location relative to the repository root.
|
| 295 |
+
message: str, optional
|
| 296 |
+
The commit message for the deletion.
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
if not self.username:
|
| 300 |
+
raise ValueError("Authentication required")
|
| 301 |
+
|
| 302 |
+
path = self._strip_protocol(path)
|
| 303 |
+
|
| 304 |
+
# Attempt to get SHA from cache or Github API
|
| 305 |
+
sha = self._get_sha_from_cache(path)
|
| 306 |
+
if not sha:
|
| 307 |
+
url = self.content_url.format(
|
| 308 |
+
org=self.org,
|
| 309 |
+
repo=self.repo,
|
| 310 |
+
path=quote(path.lstrip("/")),
|
| 311 |
+
sha=quote(self.root, safe=""),
|
| 312 |
+
)
|
| 313 |
+
r = requests.get(url, timeout=self.timeout, **self.kw)
|
| 314 |
+
if r.status_code == 404:
|
| 315 |
+
raise FileNotFoundError(path)
|
| 316 |
+
r.raise_for_status()
|
| 317 |
+
sha = r.json()["sha"]
|
| 318 |
+
|
| 319 |
+
# Delete the file
|
| 320 |
+
delete_url = self.content_url.format(
|
| 321 |
+
org=self.org,
|
| 322 |
+
repo=self.repo,
|
| 323 |
+
path=quote(path),
|
| 324 |
+
sha=quote(self.root, safe=""),
|
| 325 |
+
)
|
| 326 |
+
branch = self.root
|
| 327 |
+
data = {
|
| 328 |
+
"message": message or f"Delete {path}",
|
| 329 |
+
"sha": sha,
|
| 330 |
+
**({"branch": branch} if branch else {}),
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
r = requests.delete(delete_url, json=data, timeout=self.timeout, **self.kw)
|
| 334 |
+
error_message = r.json().get("message", "")
|
| 335 |
+
if re.search(r"Branch .+ not found", error_message):
|
| 336 |
+
error = "Remove only works when the filesystem is initialised from a branch or default (None)"
|
| 337 |
+
raise ValueError(error)
|
| 338 |
+
r.raise_for_status()
|
| 339 |
+
|
| 340 |
+
self.invalidate_cache(path)
|
| 341 |
+
|
| 342 |
+
def _get_sha_from_cache(self, path):
|
| 343 |
+
for entries in self.dircache.values():
|
| 344 |
+
for entry in entries:
|
| 345 |
+
entry_path = entry.get("name")
|
| 346 |
+
if entry_path and entry_path == path and "sha" in entry:
|
| 347 |
+
return entry["sha"]
|
| 348 |
+
return None
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/http.py
ADDED
|
@@ -0,0 +1,1069 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import io
|
| 3 |
+
import logging
|
| 4 |
+
import random
|
| 5 |
+
import re
|
| 6 |
+
import weakref
|
| 7 |
+
from copy import copy
|
| 8 |
+
from urllib.parse import urlparse
|
| 9 |
+
|
| 10 |
+
import aiohttp
|
| 11 |
+
import yarl
|
| 12 |
+
|
| 13 |
+
from fsspec.asyn import AbstractAsyncStreamedFile, AsyncFileSystem, sync, sync_wrapper
|
| 14 |
+
from fsspec.callbacks import DEFAULT_CALLBACK
|
| 15 |
+
from fsspec.exceptions import FSTimeoutError
|
| 16 |
+
from fsspec.spec import AbstractBufferedFile
|
| 17 |
+
from fsspec.utils import (
|
| 18 |
+
DEFAULT_BLOCK_SIZE,
|
| 19 |
+
glob_translate,
|
| 20 |
+
isfilelike,
|
| 21 |
+
nullcontext,
|
| 22 |
+
range_response_window,
|
| 23 |
+
response_is_requested_range,
|
| 24 |
+
tokenize,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
from ..caching import AllBytes
|
| 28 |
+
|
| 29 |
+
# https://stackoverflow.com/a/15926317/3821154
|
| 30 |
+
# The attribute scan must stay linear: it stops at the next "<" or ">" and the
|
| 31 |
+
# whitespace before href is a lookbehind rather than a second quantifier, so a
|
| 32 |
+
# page cannot make it backtrack cubically (1 KB of whitespace after "<a"
|
| 33 |
+
# used to stall ls() for seconds, 10 KB for hours).
|
| 34 |
+
ex = re.compile(r"""<(a|A)\s[^<>]*?(?<=\s)(href|HREF)=["'](?P<url>[^"']+)""")
|
| 35 |
+
ex2 = re.compile(r"""(?P<url>http[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")
|
| 36 |
+
logger = logging.getLogger("fsspec.http")
|
| 37 |
+
|
| 38 |
+
_RETRYABLE_STATUSES = frozenset({408, 425, 429, 500, 502, 503, 504})
|
| 39 |
+
# dropped or reset connections, truncated bodies, timeouts
|
| 40 |
+
_RETRYABLE_EXCEPTIONS = (
|
| 41 |
+
aiohttp.ClientConnectionError,
|
| 42 |
+
aiohttp.ClientPayloadError,
|
| 43 |
+
asyncio.TimeoutError,
|
| 44 |
+
)
|
| 45 |
+
_RETRY_MAX_WAIT = 60.0
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _is_retryable(exc, statuses=_RETRYABLE_STATUSES, exceptions=None):
|
| 49 |
+
"""Whether a failed HTTP read is worth repeating.
|
| 50 |
+
|
| 51 |
+
A response error is retried when its status is in ``statuses``; any
|
| 52 |
+
other error is retried when it is an instance of ``exceptions``. The
|
| 53 |
+
default (None) is ``_RETRYABLE_EXCEPTIONS`` minus SSL failures, which
|
| 54 |
+
are deterministic. Anything else (including the ``FileNotFoundError``/
|
| 55 |
+
``PermissionError`` a subclass may map 4xx codes to) propagates at once.
|
| 56 |
+
"""
|
| 57 |
+
if isinstance(exc, aiohttp.ClientResponseError):
|
| 58 |
+
return exc.status in statuses
|
| 59 |
+
if exceptions is None:
|
| 60 |
+
return isinstance(exc, _RETRYABLE_EXCEPTIONS) and not isinstance(
|
| 61 |
+
exc, aiohttp.ClientSSLError
|
| 62 |
+
)
|
| 63 |
+
return isinstance(exc, exceptions)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _retry_after(exc):
|
| 67 |
+
"""Delta-seconds ``Retry-After`` carried by a response error, else None."""
|
| 68 |
+
headers = getattr(exc, "headers", None)
|
| 69 |
+
if not headers:
|
| 70 |
+
return None
|
| 71 |
+
try:
|
| 72 |
+
return max(0.0, float(headers.get("Retry-After")))
|
| 73 |
+
except (TypeError, ValueError):
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
async def _with_retries(attempt, fs, label):
|
| 78 |
+
"""Await ``attempt()``, repeating it on transient failures.
|
| 79 |
+
|
| 80 |
+
``attempt`` is a zero-argument coroutine function covering the whole
|
| 81 |
+
request *and* body read, so a connection dropped mid-body counts as a
|
| 82 |
+
failure too. The policy comes from the ``retries``, ``retry_wait``,
|
| 83 |
+
``retry_statuses`` and ``retry_exceptions`` attributes of ``fs``. A
|
| 84 |
+
``Retry-After`` header is honoured when present; otherwise the wait
|
| 85 |
+
doubles from ``retry_wait`` on each retry, jittered. Either way the wait
|
| 86 |
+
is capped at ``_RETRY_MAX_WAIT`` seconds. Non-retryable errors and the
|
| 87 |
+
final failure propagate unchanged.
|
| 88 |
+
"""
|
| 89 |
+
retries = fs.retries
|
| 90 |
+
for n in range(retries + 1):
|
| 91 |
+
try:
|
| 92 |
+
return await attempt()
|
| 93 |
+
except Exception as exc:
|
| 94 |
+
if n >= retries or not _is_retryable(
|
| 95 |
+
exc, fs.retry_statuses, fs.retry_exceptions
|
| 96 |
+
):
|
| 97 |
+
raise
|
| 98 |
+
delay = _retry_after(exc)
|
| 99 |
+
if delay is None:
|
| 100 |
+
delay = fs.retry_wait * 2**n * (0.5 + random.random())
|
| 101 |
+
delay = min(_RETRY_MAX_WAIT, delay)
|
| 102 |
+
logger.warning(
|
| 103 |
+
"%s: attempt %d/%d failed (%r); retrying in %.1fs",
|
| 104 |
+
label,
|
| 105 |
+
n + 1,
|
| 106 |
+
retries + 1,
|
| 107 |
+
exc,
|
| 108 |
+
delay,
|
| 109 |
+
)
|
| 110 |
+
await asyncio.sleep(delay)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
async def get_client(**kwargs):
|
| 114 |
+
return aiohttp.ClientSession(**kwargs)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class HTTPFileSystem(AsyncFileSystem):
|
| 118 |
+
"""
|
| 119 |
+
Simple File-System for fetching data via HTTP(S)
|
| 120 |
+
|
| 121 |
+
``ls()`` is implemented by loading the parent page and doing a regex
|
| 122 |
+
match on the result. If simple_link=True, anything of the form
|
| 123 |
+
"http(s)://server.com/stuff?thing=other"; otherwise only links within
|
| 124 |
+
HTML href tags will be used.
|
| 125 |
+
|
| 126 |
+
URLs are passed unfiltered to aiohttp, so all addresses are accessible. Where URLs are
|
| 127 |
+
supplied by a user, the calling application may wish to filter to prevent scanning.
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
protocol = ("http", "https")
|
| 131 |
+
sep = "/"
|
| 132 |
+
|
| 133 |
+
def __init__(
|
| 134 |
+
self,
|
| 135 |
+
simple_links=True,
|
| 136 |
+
block_size=None,
|
| 137 |
+
same_scheme=True,
|
| 138 |
+
size_policy=None,
|
| 139 |
+
cache_type="bytes",
|
| 140 |
+
cache_options=None,
|
| 141 |
+
asynchronous=False,
|
| 142 |
+
loop=None,
|
| 143 |
+
client_kwargs=None,
|
| 144 |
+
get_client=get_client,
|
| 145 |
+
encoded=False,
|
| 146 |
+
retries=3,
|
| 147 |
+
retry_wait=1.0,
|
| 148 |
+
retry_statuses=None,
|
| 149 |
+
retry_exceptions=None,
|
| 150 |
+
**storage_options,
|
| 151 |
+
):
|
| 152 |
+
"""
|
| 153 |
+
NB: if this is called async, you must await set_client
|
| 154 |
+
|
| 155 |
+
Parameters
|
| 156 |
+
----------
|
| 157 |
+
block_size: int
|
| 158 |
+
Blocks to read bytes; if 0, will default to raw requests file-like
|
| 159 |
+
objects instead of HTTPFile instances
|
| 160 |
+
simple_links: bool
|
| 161 |
+
If True, will consider both HTML <a> tags and anything that looks
|
| 162 |
+
like a URL; if False, will consider only the former.
|
| 163 |
+
same_scheme: True
|
| 164 |
+
When doing ls/glob, if this is True, only consider paths that have
|
| 165 |
+
http/https matching the input URLs.
|
| 166 |
+
size_policy: this argument is deprecated
|
| 167 |
+
client_kwargs: dict
|
| 168 |
+
Passed to aiohttp.ClientSession, see
|
| 169 |
+
https://docs.aiohttp.org/en/stable/client_reference.html
|
| 170 |
+
For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}``
|
| 171 |
+
get_client: Callable[..., aiohttp.ClientSession]
|
| 172 |
+
A callable, which takes keyword arguments and constructs
|
| 173 |
+
an aiohttp.ClientSession. Its state will be managed by
|
| 174 |
+
the HTTPFileSystem class.
|
| 175 |
+
retries: int
|
| 176 |
+
How many times a transient failure of a read (see below)
|
| 177 |
+
is retried in ``cat_file``, ``HTTPFile`` block reads and the
|
| 178 |
+
``info`` lookup behind ``open``; 0 disables retries.
|
| 179 |
+
retry_wait: float
|
| 180 |
+
Seconds to wait before the first retry; doubled on each further
|
| 181 |
+
retry, with jitter. A ``Retry-After`` header sent by the server
|
| 182 |
+
takes precedence. Either wait is capped at 60 s.
|
| 183 |
+
retry_statuses: container of int or None
|
| 184 |
+
HTTP status codes of a failed read that are retried; default
|
| 185 |
+
(None) is 408, 425, 429, 500, 502, 503 and 504.
|
| 186 |
+
retry_exceptions: exception class, tuple of classes or None
|
| 187 |
+
Errors other than a response status that are retried; default
|
| 188 |
+
(None) is dropped or reset connections (except SSL failures),
|
| 189 |
+
truncated bodies and timeouts.
|
| 190 |
+
storage_options: key-value
|
| 191 |
+
Any other parameters passed on to requests
|
| 192 |
+
cache_type, cache_options: defaults used in open()
|
| 193 |
+
"""
|
| 194 |
+
super().__init__(self, asynchronous=asynchronous, loop=loop, **storage_options)
|
| 195 |
+
self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE
|
| 196 |
+
self.simple_links = simple_links
|
| 197 |
+
self.same_schema = same_scheme
|
| 198 |
+
self.cache_type = cache_type
|
| 199 |
+
self.cache_options = cache_options
|
| 200 |
+
self.client_kwargs = client_kwargs or {}
|
| 201 |
+
self.get_client = get_client
|
| 202 |
+
self.encoded = encoded
|
| 203 |
+
if retries < 0:
|
| 204 |
+
raise ValueError(f"retries must be >= 0, got {retries!r}")
|
| 205 |
+
if retry_wait < 0:
|
| 206 |
+
raise ValueError(f"retry_wait must be >= 0, got {retry_wait!r}")
|
| 207 |
+
self.retries = retries
|
| 208 |
+
self.retry_wait = retry_wait
|
| 209 |
+
self.retry_statuses = (
|
| 210 |
+
retry_statuses if retry_statuses is not None else _RETRYABLE_STATUSES
|
| 211 |
+
)
|
| 212 |
+
self.retry_exceptions = retry_exceptions
|
| 213 |
+
self.kwargs = storage_options
|
| 214 |
+
self._session = None
|
| 215 |
+
|
| 216 |
+
# Clean caching-related parameters from `storage_options`
|
| 217 |
+
# before propagating them as `request_options` through `self.kwargs`.
|
| 218 |
+
# TODO: Maybe rename `self.kwargs` to `self.request_options` to make
|
| 219 |
+
# it clearer.
|
| 220 |
+
request_options = copy(storage_options)
|
| 221 |
+
self.use_listings_cache = request_options.pop("use_listings_cache", False)
|
| 222 |
+
request_options.pop("listings_expiry_time", None)
|
| 223 |
+
request_options.pop("max_paths", None)
|
| 224 |
+
request_options.pop("skip_instance_cache", None)
|
| 225 |
+
self.kwargs = request_options
|
| 226 |
+
|
| 227 |
+
@property
|
| 228 |
+
def fsid(self):
|
| 229 |
+
return "http"
|
| 230 |
+
|
| 231 |
+
def encode_url(self, url):
|
| 232 |
+
return yarl.URL(url, encoded=self.encoded)
|
| 233 |
+
|
| 234 |
+
@staticmethod
|
| 235 |
+
def close_session(loop, session):
|
| 236 |
+
if loop is not None and loop.is_running():
|
| 237 |
+
try:
|
| 238 |
+
sync(loop, session.close, timeout=0.1)
|
| 239 |
+
return
|
| 240 |
+
except (TimeoutError, FSTimeoutError, NotImplementedError, RuntimeError):
|
| 241 |
+
pass
|
| 242 |
+
connector = getattr(session, "_connector", None)
|
| 243 |
+
if connector is not None:
|
| 244 |
+
# close after loop is dead
|
| 245 |
+
connector._close()
|
| 246 |
+
|
| 247 |
+
async def set_session(self):
|
| 248 |
+
if self._session is None:
|
| 249 |
+
self._session = await self.get_client(loop=self.loop, **self.client_kwargs)
|
| 250 |
+
if not self.asynchronous:
|
| 251 |
+
weakref.finalize(self, self.close_session, self.loop, self._session)
|
| 252 |
+
return self._session
|
| 253 |
+
|
| 254 |
+
@classmethod
|
| 255 |
+
def _strip_protocol(cls, path):
|
| 256 |
+
"""For HTTP, we always want to keep the full URL"""
|
| 257 |
+
return path
|
| 258 |
+
|
| 259 |
+
@classmethod
|
| 260 |
+
def _parent(cls, path):
|
| 261 |
+
# override, since _strip_protocol is different for URLs
|
| 262 |
+
par = super()._parent(path)
|
| 263 |
+
if len(par) > 7: # "http://..."
|
| 264 |
+
return par
|
| 265 |
+
return ""
|
| 266 |
+
|
| 267 |
+
async def _ls_real(self, url, detail=True, **kwargs):
|
| 268 |
+
# ignoring URL-encoded arguments
|
| 269 |
+
kw = self.kwargs.copy()
|
| 270 |
+
kw.update(kwargs)
|
| 271 |
+
logger.debug(url)
|
| 272 |
+
session = await self.set_session()
|
| 273 |
+
async with session.get(self.encode_url(url), **kw) as r:
|
| 274 |
+
self._raise_not_found_for_status(r, url)
|
| 275 |
+
|
| 276 |
+
if "Content-Type" in r.headers:
|
| 277 |
+
mimetype = r.headers["Content-Type"].partition(";")[0]
|
| 278 |
+
else:
|
| 279 |
+
mimetype = None
|
| 280 |
+
|
| 281 |
+
if mimetype in ("text/html", None):
|
| 282 |
+
try:
|
| 283 |
+
text = await r.text(errors="ignore")
|
| 284 |
+
if self.simple_links:
|
| 285 |
+
links = ex2.findall(text) + [u[2] for u in ex.findall(text)]
|
| 286 |
+
else:
|
| 287 |
+
links = [u[2] for u in ex.findall(text)]
|
| 288 |
+
except UnicodeDecodeError:
|
| 289 |
+
links = [] # binary, not HTML
|
| 290 |
+
else:
|
| 291 |
+
links = []
|
| 292 |
+
|
| 293 |
+
out = set()
|
| 294 |
+
parts = urlparse(url)
|
| 295 |
+
for l in links:
|
| 296 |
+
if isinstance(l, tuple):
|
| 297 |
+
l = l[1]
|
| 298 |
+
if l.startswith("/") and len(l) > 1:
|
| 299 |
+
# absolute URL on this server
|
| 300 |
+
l = f"{parts.scheme}://{parts.netloc}{l}"
|
| 301 |
+
if l.startswith("http"):
|
| 302 |
+
if self.same_schema and l.startswith(url.rstrip("/") + "/"):
|
| 303 |
+
out.add(l)
|
| 304 |
+
elif l.replace("https", "http").startswith(
|
| 305 |
+
url.replace("https", "http").rstrip("/") + "/"
|
| 306 |
+
):
|
| 307 |
+
# allowed to cross http <-> https
|
| 308 |
+
out.add(l)
|
| 309 |
+
else:
|
| 310 |
+
if l not in ["..", "../"]:
|
| 311 |
+
# Ignore FTP-like "parent"
|
| 312 |
+
out.add("/".join([url.rstrip("/"), l.lstrip("/")]))
|
| 313 |
+
if not out and url.endswith("/"):
|
| 314 |
+
out = await self._ls_real(url.rstrip("/"), detail=False, **kwargs)
|
| 315 |
+
if detail:
|
| 316 |
+
return [
|
| 317 |
+
{
|
| 318 |
+
"name": u,
|
| 319 |
+
"size": None,
|
| 320 |
+
"type": "directory" if u.endswith("/") else "file",
|
| 321 |
+
}
|
| 322 |
+
for u in out
|
| 323 |
+
]
|
| 324 |
+
else:
|
| 325 |
+
return sorted(out)
|
| 326 |
+
|
| 327 |
+
async def _ls(self, url, detail=True, **kwargs):
|
| 328 |
+
if self.use_listings_cache and url in self.dircache:
|
| 329 |
+
out = self.dircache[url]
|
| 330 |
+
else:
|
| 331 |
+
out = await self._ls_real(url, detail=True, **kwargs)
|
| 332 |
+
self.dircache[url] = out
|
| 333 |
+
if detail:
|
| 334 |
+
return out
|
| 335 |
+
return sorted(entry["name"] for entry in out)
|
| 336 |
+
|
| 337 |
+
ls = sync_wrapper(_ls)
|
| 338 |
+
|
| 339 |
+
def _raise_not_found_for_status(self, response, url):
|
| 340 |
+
"""
|
| 341 |
+
Raises FileNotFoundError for 404s, otherwise uses raise_for_status.
|
| 342 |
+
"""
|
| 343 |
+
if response.status == 404:
|
| 344 |
+
raise FileNotFoundError(url)
|
| 345 |
+
response.raise_for_status()
|
| 346 |
+
|
| 347 |
+
async def _cat_file(self, url, start=None, end=None, **kwargs):
|
| 348 |
+
kw = self.kwargs.copy()
|
| 349 |
+
kw.update(kwargs)
|
| 350 |
+
logger.debug(url)
|
| 351 |
+
|
| 352 |
+
ranged = start is not None or end is not None
|
| 353 |
+
if ranged:
|
| 354 |
+
if start == end or (start is None and end == 0):
|
| 355 |
+
return b""
|
| 356 |
+
headers = kw.pop("headers", {}).copy()
|
| 357 |
+
|
| 358 |
+
headers["Range"] = await self._process_limits(url, start, end)
|
| 359 |
+
kw["headers"] = headers
|
| 360 |
+
session = await self.set_session()
|
| 361 |
+
|
| 362 |
+
async def _once():
|
| 363 |
+
async with session.get(self.encode_url(url), **kw) as r:
|
| 364 |
+
out = await r.read()
|
| 365 |
+
self._raise_not_found_for_status(r, url)
|
| 366 |
+
# a server that ignores the Range header replies with the whole
|
| 367 |
+
# file, which is not the window the caller asked for
|
| 368 |
+
return (
|
| 369 |
+
range_response_window(out, r.status, r.headers, start, end)
|
| 370 |
+
if ranged
|
| 371 |
+
else out
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
return await _with_retries(_once, self, url)
|
| 375 |
+
|
| 376 |
+
async def _get_file(
|
| 377 |
+
self, rpath, lpath, chunk_size=5 * 2**20, callback=DEFAULT_CALLBACK, **kwargs
|
| 378 |
+
):
|
| 379 |
+
kw = self.kwargs.copy()
|
| 380 |
+
kw.update(kwargs)
|
| 381 |
+
logger.debug(rpath)
|
| 382 |
+
session = await self.set_session()
|
| 383 |
+
async with session.get(self.encode_url(rpath), **kw) as r:
|
| 384 |
+
try:
|
| 385 |
+
size = int(r.headers["content-length"])
|
| 386 |
+
except (ValueError, KeyError):
|
| 387 |
+
size = None
|
| 388 |
+
|
| 389 |
+
callback.set_size(size)
|
| 390 |
+
self._raise_not_found_for_status(r, rpath)
|
| 391 |
+
if isfilelike(lpath):
|
| 392 |
+
outfile = lpath
|
| 393 |
+
else:
|
| 394 |
+
outfile = open(lpath, "wb") # noqa: ASYNC230
|
| 395 |
+
|
| 396 |
+
try:
|
| 397 |
+
chunk = True
|
| 398 |
+
while chunk:
|
| 399 |
+
chunk = await r.content.read(chunk_size)
|
| 400 |
+
outfile.write(chunk)
|
| 401 |
+
callback.relative_update(len(chunk))
|
| 402 |
+
finally:
|
| 403 |
+
if not isfilelike(lpath):
|
| 404 |
+
outfile.close()
|
| 405 |
+
|
| 406 |
+
async def _put_file(
|
| 407 |
+
self,
|
| 408 |
+
lpath,
|
| 409 |
+
rpath,
|
| 410 |
+
chunk_size=5 * 2**20,
|
| 411 |
+
callback=DEFAULT_CALLBACK,
|
| 412 |
+
method="post",
|
| 413 |
+
mode="overwrite",
|
| 414 |
+
**kwargs,
|
| 415 |
+
):
|
| 416 |
+
if mode != "overwrite":
|
| 417 |
+
raise NotImplementedError("Exclusive write")
|
| 418 |
+
|
| 419 |
+
async def gen_chunks():
|
| 420 |
+
# Support passing arbitrary file-like objects
|
| 421 |
+
# and use them instead of streams.
|
| 422 |
+
if isinstance(lpath, io.IOBase):
|
| 423 |
+
context = nullcontext(lpath)
|
| 424 |
+
use_seek = False # might not support seeking
|
| 425 |
+
else:
|
| 426 |
+
context = open(lpath, "rb") # noqa: ASYNC230
|
| 427 |
+
use_seek = True
|
| 428 |
+
|
| 429 |
+
with context as f:
|
| 430 |
+
if use_seek:
|
| 431 |
+
callback.set_size(f.seek(0, 2))
|
| 432 |
+
f.seek(0)
|
| 433 |
+
else:
|
| 434 |
+
callback.set_size(getattr(f, "size", None))
|
| 435 |
+
|
| 436 |
+
chunk = f.read(chunk_size)
|
| 437 |
+
while chunk:
|
| 438 |
+
yield chunk
|
| 439 |
+
callback.relative_update(len(chunk))
|
| 440 |
+
chunk = f.read(chunk_size)
|
| 441 |
+
|
| 442 |
+
kw = self.kwargs.copy()
|
| 443 |
+
kw.update(kwargs)
|
| 444 |
+
session = await self.set_session()
|
| 445 |
+
|
| 446 |
+
method = method.lower()
|
| 447 |
+
if method not in ("post", "put"):
|
| 448 |
+
raise ValueError(
|
| 449 |
+
f"method has to be either 'post' or 'put', not: {method!r}"
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
meth = getattr(session, method)
|
| 453 |
+
async with meth(self.encode_url(rpath), data=gen_chunks(), **kw) as resp:
|
| 454 |
+
self._raise_not_found_for_status(resp, rpath)
|
| 455 |
+
|
| 456 |
+
async def _exists(self, path, strict=False, **kwargs):
|
| 457 |
+
kw = self.kwargs.copy()
|
| 458 |
+
kw.update(kwargs)
|
| 459 |
+
try:
|
| 460 |
+
logger.debug(path)
|
| 461 |
+
session = await self.set_session()
|
| 462 |
+
r = await session.get(self.encode_url(path), **kw)
|
| 463 |
+
async with r:
|
| 464 |
+
if strict:
|
| 465 |
+
self._raise_not_found_for_status(r, path)
|
| 466 |
+
return r.status < 400
|
| 467 |
+
except FileNotFoundError:
|
| 468 |
+
return False
|
| 469 |
+
except aiohttp.ClientError:
|
| 470 |
+
if strict:
|
| 471 |
+
raise
|
| 472 |
+
return False
|
| 473 |
+
|
| 474 |
+
async def _isfile(self, path, **kwargs):
|
| 475 |
+
return await self._exists(path, **kwargs)
|
| 476 |
+
|
| 477 |
+
def _open(
|
| 478 |
+
self,
|
| 479 |
+
path,
|
| 480 |
+
mode="rb",
|
| 481 |
+
block_size=None,
|
| 482 |
+
autocommit=None, # XXX: This differs from the base class.
|
| 483 |
+
cache_type=None,
|
| 484 |
+
cache_options=None,
|
| 485 |
+
size=None,
|
| 486 |
+
**kwargs,
|
| 487 |
+
):
|
| 488 |
+
"""Make a file-like object
|
| 489 |
+
|
| 490 |
+
Parameters
|
| 491 |
+
----------
|
| 492 |
+
path: str
|
| 493 |
+
Full URL with protocol
|
| 494 |
+
mode: string
|
| 495 |
+
must be "rb"
|
| 496 |
+
block_size: int or None
|
| 497 |
+
Bytes to download in one request; use instance value if None. If
|
| 498 |
+
zero, will return a streaming Requests file-like instance.
|
| 499 |
+
kwargs: key-value
|
| 500 |
+
Any other parameters, passed to requests calls
|
| 501 |
+
"""
|
| 502 |
+
if mode != "rb":
|
| 503 |
+
raise NotImplementedError
|
| 504 |
+
block_size = block_size if block_size is not None else self.block_size
|
| 505 |
+
kw = self.kwargs.copy()
|
| 506 |
+
kw["asynchronous"] = self.asynchronous
|
| 507 |
+
kw.update(kwargs)
|
| 508 |
+
info = {}
|
| 509 |
+
size = size or info.update(self.info(path, **kwargs)) or info["size"]
|
| 510 |
+
session = sync(self.loop, self.set_session)
|
| 511 |
+
if block_size and size and info.get("partial", True):
|
| 512 |
+
return HTTPFile(
|
| 513 |
+
self,
|
| 514 |
+
path,
|
| 515 |
+
session=session,
|
| 516 |
+
block_size=block_size,
|
| 517 |
+
mode=mode,
|
| 518 |
+
size=size,
|
| 519 |
+
cache_type=cache_type or self.cache_type,
|
| 520 |
+
cache_options=cache_options or self.cache_options,
|
| 521 |
+
loop=self.loop,
|
| 522 |
+
**kw,
|
| 523 |
+
)
|
| 524 |
+
else:
|
| 525 |
+
return HTTPStreamFile(
|
| 526 |
+
self,
|
| 527 |
+
path,
|
| 528 |
+
mode=mode,
|
| 529 |
+
loop=self.loop,
|
| 530 |
+
session=session,
|
| 531 |
+
**kw,
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
async def open_async(self, path, mode="rb", size=None, **kwargs):
|
| 535 |
+
session = await self.set_session()
|
| 536 |
+
if size is None:
|
| 537 |
+
try:
|
| 538 |
+
size = (await self._info(path, **kwargs))["size"]
|
| 539 |
+
except FileNotFoundError:
|
| 540 |
+
pass
|
| 541 |
+
return AsyncStreamFile(
|
| 542 |
+
self,
|
| 543 |
+
path,
|
| 544 |
+
loop=self.loop,
|
| 545 |
+
session=session,
|
| 546 |
+
size=size,
|
| 547 |
+
**kwargs,
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
def ukey(self, url):
|
| 551 |
+
"""Unique identifier; assume HTTP files are static, unchanging"""
|
| 552 |
+
return tokenize(url, self.kwargs, self.protocol)
|
| 553 |
+
|
| 554 |
+
async def _info(self, url, **kwargs):
|
| 555 |
+
"""Get info of URL
|
| 556 |
+
|
| 557 |
+
Tries to access location via HEAD, and then GET methods, but does
|
| 558 |
+
not fetch the data.
|
| 559 |
+
|
| 560 |
+
It is possible that the server does not supply any size information, in
|
| 561 |
+
which case size will be given as None (and certain operations on the
|
| 562 |
+
corresponding file will not work).
|
| 563 |
+
"""
|
| 564 |
+
info = {}
|
| 565 |
+
session = await self.set_session()
|
| 566 |
+
|
| 567 |
+
async def _once():
|
| 568 |
+
# HEAD, then GET if that gave no size or failed for any reason
|
| 569 |
+
# (many servers mishandle HEAD); only a GET failure counts as a
|
| 570 |
+
# failed attempt.
|
| 571 |
+
for policy in ["head", "get"]:
|
| 572 |
+
try:
|
| 573 |
+
info.update(
|
| 574 |
+
await _file_info(
|
| 575 |
+
self.encode_url(url),
|
| 576 |
+
size_policy=policy,
|
| 577 |
+
session=session,
|
| 578 |
+
**self.kwargs,
|
| 579 |
+
**kwargs,
|
| 580 |
+
)
|
| 581 |
+
)
|
| 582 |
+
if info.get("size") is not None:
|
| 583 |
+
break
|
| 584 |
+
except Exception as exc:
|
| 585 |
+
if policy == "get":
|
| 586 |
+
raise
|
| 587 |
+
logger.debug("", exc_info=exc)
|
| 588 |
+
|
| 589 |
+
try:
|
| 590 |
+
await _with_retries(_once, self, url)
|
| 591 |
+
except Exception as exc:
|
| 592 |
+
# If get failed, then raise a FileNotFoundError
|
| 593 |
+
raise FileNotFoundError(url) from exc
|
| 594 |
+
|
| 595 |
+
return {"name": url, "size": None, **info, "type": "file"}
|
| 596 |
+
|
| 597 |
+
async def _glob(self, path, maxdepth=None, **kwargs):
|
| 598 |
+
"""
|
| 599 |
+
Find files by glob-matching.
|
| 600 |
+
|
| 601 |
+
This implementation is idntical to the one in AbstractFileSystem,
|
| 602 |
+
but "?" is not considered as a character for globbing, because it is
|
| 603 |
+
so common in URLs, often identifying the "query" part.
|
| 604 |
+
"""
|
| 605 |
+
if maxdepth is not None and maxdepth < 1:
|
| 606 |
+
raise ValueError("maxdepth must be at least 1")
|
| 607 |
+
import re
|
| 608 |
+
|
| 609 |
+
ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash
|
| 610 |
+
path = self._strip_protocol(path)
|
| 611 |
+
append_slash_to_dirname = ends_with_slash or path.endswith(("/**", "/*"))
|
| 612 |
+
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
|
| 613 |
+
idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
|
| 614 |
+
|
| 615 |
+
min_idx = min(idx_star, idx_brace)
|
| 616 |
+
|
| 617 |
+
detail = kwargs.pop("detail", False)
|
| 618 |
+
|
| 619 |
+
if not has_magic(path):
|
| 620 |
+
if await self._exists(path, **kwargs):
|
| 621 |
+
if not detail:
|
| 622 |
+
return [path]
|
| 623 |
+
else:
|
| 624 |
+
return {path: await self._info(path, **kwargs)}
|
| 625 |
+
else:
|
| 626 |
+
if not detail:
|
| 627 |
+
return [] # glob of non-existent returns empty
|
| 628 |
+
else:
|
| 629 |
+
return {}
|
| 630 |
+
elif "/" in path[:min_idx]:
|
| 631 |
+
min_idx = path[:min_idx].rindex("/")
|
| 632 |
+
root = path[: min_idx + 1]
|
| 633 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 634 |
+
else:
|
| 635 |
+
root = ""
|
| 636 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 637 |
+
|
| 638 |
+
if "**" in path:
|
| 639 |
+
if maxdepth is not None:
|
| 640 |
+
idx_double_stars = path.find("**")
|
| 641 |
+
depth_double_stars = path[idx_double_stars:].count("/") + 1
|
| 642 |
+
depth = depth - depth_double_stars + maxdepth
|
| 643 |
+
else:
|
| 644 |
+
depth = None
|
| 645 |
+
|
| 646 |
+
allpaths = await self._find(
|
| 647 |
+
root, maxdepth=depth, withdirs=True, detail=True, **kwargs
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
pattern = glob_translate(path + ("/" if ends_with_slash else ""))
|
| 651 |
+
pattern = re.compile(pattern)
|
| 652 |
+
|
| 653 |
+
out = {
|
| 654 |
+
(
|
| 655 |
+
p.rstrip("/")
|
| 656 |
+
if not append_slash_to_dirname
|
| 657 |
+
and info["type"] == "directory"
|
| 658 |
+
and p.endswith("/")
|
| 659 |
+
else p
|
| 660 |
+
): info
|
| 661 |
+
for p, info in sorted(allpaths.items())
|
| 662 |
+
if pattern.match(p.rstrip("/"))
|
| 663 |
+
}
|
| 664 |
+
|
| 665 |
+
if detail:
|
| 666 |
+
return out
|
| 667 |
+
else:
|
| 668 |
+
return list(out)
|
| 669 |
+
|
| 670 |
+
async def _isdir(self, path):
|
| 671 |
+
# override, since all URLs are (also) files
|
| 672 |
+
try:
|
| 673 |
+
return bool(await self._ls(path))
|
| 674 |
+
except (FileNotFoundError, ValueError):
|
| 675 |
+
return False
|
| 676 |
+
|
| 677 |
+
async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
|
| 678 |
+
"""
|
| 679 |
+
Write bytes to a remote file over HTTP.
|
| 680 |
+
|
| 681 |
+
Parameters
|
| 682 |
+
----------
|
| 683 |
+
path : str
|
| 684 |
+
Target URL where the data should be written
|
| 685 |
+
value : bytes
|
| 686 |
+
Data to be written
|
| 687 |
+
mode : str
|
| 688 |
+
Only 'overwrite' is accepted, allowing an unconditional PUT request.
|
| 689 |
+
The server determines PUT behavior, so other modes are rejected
|
| 690 |
+
defensively rather than assuming append or create semantics.
|
| 691 |
+
**kwargs : dict
|
| 692 |
+
Additional parameters to pass to the HTTP request
|
| 693 |
+
"""
|
| 694 |
+
if mode != "overwrite":
|
| 695 |
+
raise ValueError(
|
| 696 |
+
"HTTP pipe_file only accepts mode='overwrite'; "
|
| 697 |
+
"PUT behavior is server-dependent, so other modes are "
|
| 698 |
+
"rejected defensively"
|
| 699 |
+
)
|
| 700 |
+
url = self._strip_protocol(path)
|
| 701 |
+
headers = kwargs.pop("headers", {})
|
| 702 |
+
headers["Content-Length"] = str(len(value))
|
| 703 |
+
|
| 704 |
+
session = await self.set_session()
|
| 705 |
+
|
| 706 |
+
async with session.put(
|
| 707 |
+
self.encode_url(url), data=value, headers=headers, **kwargs
|
| 708 |
+
) as r:
|
| 709 |
+
r.raise_for_status()
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
class HTTPFile(AbstractBufferedFile):
|
| 713 |
+
"""
|
| 714 |
+
A file-like object pointing to a remote HTTP(S) resource
|
| 715 |
+
|
| 716 |
+
Supports only reading, with read-ahead of a predetermined block-size.
|
| 717 |
+
|
| 718 |
+
In the case that the server does not supply the filesize, only reading of
|
| 719 |
+
the complete file in one go is supported.
|
| 720 |
+
|
| 721 |
+
Parameters
|
| 722 |
+
----------
|
| 723 |
+
url: str
|
| 724 |
+
Full URL of the remote resource, including the protocol
|
| 725 |
+
session: aiohttp.ClientSession or None
|
| 726 |
+
All calls will be made within this session, to avoid restarting
|
| 727 |
+
connections where the server allows this
|
| 728 |
+
block_size: int or None
|
| 729 |
+
The amount of read-ahead to do, in bytes. Default is 5MB, or the value
|
| 730 |
+
configured for the FileSystem creating this file
|
| 731 |
+
size: None or int
|
| 732 |
+
If given, this is the size of the file in bytes, and we don't attempt
|
| 733 |
+
to call the server to find the value.
|
| 734 |
+
kwargs: all other key-values are passed to requests calls.
|
| 735 |
+
"""
|
| 736 |
+
|
| 737 |
+
def __init__(
|
| 738 |
+
self,
|
| 739 |
+
fs,
|
| 740 |
+
url,
|
| 741 |
+
session=None,
|
| 742 |
+
block_size=None,
|
| 743 |
+
mode="rb",
|
| 744 |
+
cache_type="bytes",
|
| 745 |
+
cache_options=None,
|
| 746 |
+
size=None,
|
| 747 |
+
loop=None,
|
| 748 |
+
asynchronous=False,
|
| 749 |
+
**kwargs,
|
| 750 |
+
):
|
| 751 |
+
if mode != "rb":
|
| 752 |
+
raise NotImplementedError("File mode not supported")
|
| 753 |
+
self.asynchronous = asynchronous
|
| 754 |
+
self.loop = loop
|
| 755 |
+
self.url = url
|
| 756 |
+
self.session = session
|
| 757 |
+
self.details = {"name": url, "size": size, "type": "file"}
|
| 758 |
+
super().__init__(
|
| 759 |
+
fs=fs,
|
| 760 |
+
path=url,
|
| 761 |
+
mode=mode,
|
| 762 |
+
block_size=block_size,
|
| 763 |
+
cache_type=cache_type,
|
| 764 |
+
cache_options=cache_options,
|
| 765 |
+
**kwargs,
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
def read(self, length=-1):
|
| 769 |
+
"""Read bytes from file
|
| 770 |
+
|
| 771 |
+
Parameters
|
| 772 |
+
----------
|
| 773 |
+
length: int
|
| 774 |
+
Read up to this many bytes. If negative, read all content to end of
|
| 775 |
+
file. If the server has not supplied the filesize, attempting to
|
| 776 |
+
read only part of the data will raise a ValueError.
|
| 777 |
+
"""
|
| 778 |
+
if (
|
| 779 |
+
(length < 0 and self.loc == 0) # explicit read all
|
| 780 |
+
# but not when the size is known and fits into a block anyways
|
| 781 |
+
and not (self.size is not None and self.size <= self.blocksize)
|
| 782 |
+
):
|
| 783 |
+
self._fetch_all()
|
| 784 |
+
if self.size is None:
|
| 785 |
+
if length < 0:
|
| 786 |
+
self._fetch_all()
|
| 787 |
+
else:
|
| 788 |
+
length = min(self.size - self.loc, length)
|
| 789 |
+
return super().read(length)
|
| 790 |
+
|
| 791 |
+
async def async_fetch_all(self):
|
| 792 |
+
"""Read whole file in one shot, without caching
|
| 793 |
+
|
| 794 |
+
This is only called when position is still at zero,
|
| 795 |
+
and read() is called without a byte-count.
|
| 796 |
+
"""
|
| 797 |
+
logger.debug(f"Fetch all for {self}")
|
| 798 |
+
if not isinstance(self.cache, AllBytes):
|
| 799 |
+
r = await self.session.get(self.fs.encode_url(self.url), **self.kwargs)
|
| 800 |
+
async with r:
|
| 801 |
+
r.raise_for_status()
|
| 802 |
+
out = await r.read()
|
| 803 |
+
self.cache = AllBytes(
|
| 804 |
+
size=len(out), fetcher=None, blocksize=None, data=out
|
| 805 |
+
)
|
| 806 |
+
self.size = len(out)
|
| 807 |
+
|
| 808 |
+
_fetch_all = sync_wrapper(async_fetch_all)
|
| 809 |
+
|
| 810 |
+
async def async_fetch_range(self, start, end):
|
| 811 |
+
"""Download a block of data
|
| 812 |
+
|
| 813 |
+
The expectation is that the server returns only the requested bytes,
|
| 814 |
+
with HTTP code 206. If this is not the case, we first check the headers,
|
| 815 |
+
and then stream the output - if the data size is bigger than we
|
| 816 |
+
requested, an exception is raised.
|
| 817 |
+
"""
|
| 818 |
+
logger.debug(f"Fetch range for {self}: {start}-{end}")
|
| 819 |
+
kwargs = self.kwargs.copy()
|
| 820 |
+
headers = kwargs.pop("headers", {}).copy()
|
| 821 |
+
headers["Range"] = f"bytes={start}-{end - 1}"
|
| 822 |
+
if not any(k.lower() == "accept-encoding" for k in headers) and not any(
|
| 823 |
+
k.lower() == "accept-encoding" for k in self.session.headers
|
| 824 |
+
):
|
| 825 |
+
# Match the unencoded size from _file_info unless explicitly overridden.
|
| 826 |
+
headers["Accept-Encoding"] = "identity"
|
| 827 |
+
logger.debug(f"{self.url} : {headers['Range']}")
|
| 828 |
+
|
| 829 |
+
async def _once():
|
| 830 |
+
r = await self.session.get(
|
| 831 |
+
self.fs.encode_url(self.url), headers=headers, **kwargs
|
| 832 |
+
)
|
| 833 |
+
async with r:
|
| 834 |
+
if r.status == 416:
|
| 835 |
+
if self.size is not None and start < self.size:
|
| 836 |
+
# CloudFront answers 416 (with an HTML error page as
|
| 837 |
+
# body) to a range inside the file when range requests
|
| 838 |
+
# follow each other too quickly; treating it as EOF
|
| 839 |
+
# would silently truncate the read, retrying with
|
| 840 |
+
# backoff gets the data. See
|
| 841 |
+
# https://github.com/fsspec/filesystem_spec/issues/1895
|
| 842 |
+
raise aiohttp.ClientPayloadError(
|
| 843 |
+
f"{headers['Range']} of {self.url} reported "
|
| 844 |
+
f"unsatisfiable, but the file has {self.size} bytes"
|
| 845 |
+
)
|
| 846 |
+
# range request outside file
|
| 847 |
+
return b""
|
| 848 |
+
r.raise_for_status()
|
| 849 |
+
|
| 850 |
+
# If the server has handled the range request, it should reply
|
| 851 |
+
# with status 206 (partial content). But we'll guess that a
|
| 852 |
+
# suitable Content-Range header or a Content-Length no more
|
| 853 |
+
# than the requested range also mean we have got the desired
|
| 854 |
+
# range.
|
| 855 |
+
response_is_range = response_is_requested_range(
|
| 856 |
+
r.status, r.headers, start, end
|
| 857 |
+
)
|
| 858 |
+
|
| 859 |
+
if response_is_range:
|
| 860 |
+
# partial content, as expected
|
| 861 |
+
out = await r.read()
|
| 862 |
+
if self.size is not None:
|
| 863 |
+
expected = min(end, self.size) - start
|
| 864 |
+
if len(out) < expected:
|
| 865 |
+
# short body with consistent headers: a truncated
|
| 866 |
+
# block would otherwise be served from the cache
|
| 867 |
+
raise aiohttp.ClientPayloadError(
|
| 868 |
+
f"{headers['Range']} of {self.url} returned "
|
| 869 |
+
f"{len(out)} bytes, expected {expected}"
|
| 870 |
+
)
|
| 871 |
+
elif start > 0:
|
| 872 |
+
raise ValueError(
|
| 873 |
+
"The HTTP server doesn't appear to support range "
|
| 874 |
+
"requests. Only reading this file from the beginning "
|
| 875 |
+
"is supported. Open with block_size=0 for a streaming "
|
| 876 |
+
"file interface."
|
| 877 |
+
)
|
| 878 |
+
else:
|
| 879 |
+
# Response is not a range, but we want the start of the
|
| 880 |
+
# file, so we can read the required amount anyway.
|
| 881 |
+
cl = 0
|
| 882 |
+
out = []
|
| 883 |
+
while True:
|
| 884 |
+
chunk = await r.content.read(2**20)
|
| 885 |
+
# data size unknown, let's read until we have enough
|
| 886 |
+
if chunk:
|
| 887 |
+
out.append(chunk)
|
| 888 |
+
cl += len(chunk)
|
| 889 |
+
if cl > end - start:
|
| 890 |
+
break
|
| 891 |
+
else:
|
| 892 |
+
break
|
| 893 |
+
out = b"".join(out)[: end - start]
|
| 894 |
+
return out
|
| 895 |
+
|
| 896 |
+
return await _with_retries(_once, self.fs, f"{self.url} ({headers['Range']})")
|
| 897 |
+
|
| 898 |
+
_fetch_range = sync_wrapper(async_fetch_range)
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
magic_check = re.compile("([*[])")
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
def has_magic(s):
|
| 905 |
+
match = magic_check.search(s)
|
| 906 |
+
return match is not None
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
class HTTPStreamFile(AbstractBufferedFile):
|
| 910 |
+
def __init__(self, fs, url, mode="rb", loop=None, session=None, **kwargs):
|
| 911 |
+
self.asynchronous = kwargs.pop("asynchronous", False)
|
| 912 |
+
self.url = url
|
| 913 |
+
self.loop = loop
|
| 914 |
+
self.session = session
|
| 915 |
+
if mode != "rb":
|
| 916 |
+
raise ValueError
|
| 917 |
+
self.details = {"name": url, "size": None}
|
| 918 |
+
super().__init__(fs=fs, path=url, mode=mode, cache_type="none", **kwargs)
|
| 919 |
+
|
| 920 |
+
async def cor():
|
| 921 |
+
r = await self.session.get(self.fs.encode_url(url), **kwargs).__aenter__()
|
| 922 |
+
self.fs._raise_not_found_for_status(r, url)
|
| 923 |
+
return r
|
| 924 |
+
|
| 925 |
+
self.r = sync(self.loop, cor)
|
| 926 |
+
self.loop = fs.loop
|
| 927 |
+
|
| 928 |
+
def seek(self, loc, whence=0):
|
| 929 |
+
if loc == 0 and whence == 1:
|
| 930 |
+
return self.loc
|
| 931 |
+
if loc == self.loc and whence == 0:
|
| 932 |
+
return self.loc
|
| 933 |
+
raise ValueError("Cannot seek streaming HTTP file")
|
| 934 |
+
|
| 935 |
+
async def _read(self, num=-1):
|
| 936 |
+
out = await self.r.content.read(num)
|
| 937 |
+
self.loc += len(out)
|
| 938 |
+
return out
|
| 939 |
+
|
| 940 |
+
read = sync_wrapper(_read)
|
| 941 |
+
|
| 942 |
+
async def _close(self):
|
| 943 |
+
self.r.close()
|
| 944 |
+
|
| 945 |
+
def close(self):
|
| 946 |
+
asyncio.run_coroutine_threadsafe(self._close(), self.loop)
|
| 947 |
+
super().close()
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
class AsyncStreamFile(AbstractAsyncStreamedFile):
|
| 951 |
+
def __init__(
|
| 952 |
+
self, fs, url, mode="rb", loop=None, session=None, size=None, **kwargs
|
| 953 |
+
):
|
| 954 |
+
self.url = url
|
| 955 |
+
self.session = session
|
| 956 |
+
self.r = None
|
| 957 |
+
if mode != "rb":
|
| 958 |
+
raise ValueError
|
| 959 |
+
self.details = {"name": url, "size": None}
|
| 960 |
+
self.kwargs = kwargs
|
| 961 |
+
super().__init__(fs=fs, path=url, mode=mode, cache_type="none")
|
| 962 |
+
self.size = size
|
| 963 |
+
|
| 964 |
+
def seek(self, loc, whence=0):
|
| 965 |
+
if loc == 0 and whence == 1:
|
| 966 |
+
return self.loc
|
| 967 |
+
if loc == self.loc and whence == 0:
|
| 968 |
+
return self.loc
|
| 969 |
+
raise ValueError("Cannot seek streaming HTTP file")
|
| 970 |
+
|
| 971 |
+
def seekable(self):
|
| 972 |
+
return False
|
| 973 |
+
|
| 974 |
+
async def read(self, num=-1):
|
| 975 |
+
if self.closed:
|
| 976 |
+
raise ValueError("I/O operation on closed file.")
|
| 977 |
+
if self.r is None:
|
| 978 |
+
r = await self.session.get(
|
| 979 |
+
self.fs.encode_url(self.url), **self.kwargs
|
| 980 |
+
).__aenter__()
|
| 981 |
+
self.fs._raise_not_found_for_status(r, self.url)
|
| 982 |
+
self.r = r
|
| 983 |
+
out = await self.r.content.read(num)
|
| 984 |
+
self.loc += len(out)
|
| 985 |
+
return out
|
| 986 |
+
|
| 987 |
+
async def close(self):
|
| 988 |
+
if self.r is not None:
|
| 989 |
+
self.r.close()
|
| 990 |
+
self.r = None
|
| 991 |
+
await super().close()
|
| 992 |
+
|
| 993 |
+
|
| 994 |
+
async def get_range(session, url, start, end, file=None, **kwargs):
|
| 995 |
+
# explicit get a range when we know it must be safe
|
| 996 |
+
kwargs = kwargs.copy()
|
| 997 |
+
headers = kwargs.pop("headers", {}).copy()
|
| 998 |
+
headers["Range"] = f"bytes={start}-{end - 1}"
|
| 999 |
+
r = await session.get(url, headers=headers, **kwargs)
|
| 1000 |
+
r.raise_for_status()
|
| 1001 |
+
async with r:
|
| 1002 |
+
out = await r.read()
|
| 1003 |
+
if file:
|
| 1004 |
+
with open(file, "r+b") as f: # noqa: ASYNC230
|
| 1005 |
+
f.seek(start)
|
| 1006 |
+
f.write(out)
|
| 1007 |
+
else:
|
| 1008 |
+
return out
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
async def _file_info(url, session, size_policy="head", **kwargs):
|
| 1012 |
+
"""Call HEAD on the server to get details about the file (size/checksum etc.)
|
| 1013 |
+
|
| 1014 |
+
Default operation is to explicitly allow redirects and use encoding
|
| 1015 |
+
'identity' (no compression) to get the true size of the target.
|
| 1016 |
+
"""
|
| 1017 |
+
logger.debug("Retrieve file size for %s", url)
|
| 1018 |
+
kwargs = kwargs.copy()
|
| 1019 |
+
ar = kwargs.pop("allow_redirects", True)
|
| 1020 |
+
head = kwargs.get("headers", {}).copy()
|
| 1021 |
+
head["Accept-Encoding"] = "identity"
|
| 1022 |
+
kwargs["headers"] = head
|
| 1023 |
+
|
| 1024 |
+
info = {}
|
| 1025 |
+
if size_policy == "head":
|
| 1026 |
+
r = await session.head(url, allow_redirects=ar, **kwargs)
|
| 1027 |
+
elif size_policy == "get":
|
| 1028 |
+
r = await session.get(url, allow_redirects=ar, **kwargs)
|
| 1029 |
+
else:
|
| 1030 |
+
raise TypeError(f'size_policy must be "head" or "get", got {size_policy}')
|
| 1031 |
+
async with r:
|
| 1032 |
+
r.raise_for_status()
|
| 1033 |
+
|
| 1034 |
+
if "Content-Length" in r.headers:
|
| 1035 |
+
# Some servers may choose to ignore Accept-Encoding and return
|
| 1036 |
+
# compressed content, in which case the returned size is unreliable.
|
| 1037 |
+
if "Content-Encoding" not in r.headers or r.headers["Content-Encoding"] in [
|
| 1038 |
+
"identity",
|
| 1039 |
+
"",
|
| 1040 |
+
]:
|
| 1041 |
+
info["size"] = int(r.headers["Content-Length"])
|
| 1042 |
+
elif "Content-Range" in r.headers:
|
| 1043 |
+
info["size"] = int(r.headers["Content-Range"].split("/")[1])
|
| 1044 |
+
|
| 1045 |
+
if "Content-Type" in r.headers:
|
| 1046 |
+
info["mimetype"] = r.headers["Content-Type"].partition(";")[0]
|
| 1047 |
+
|
| 1048 |
+
if r.headers.get("Accept-Ranges") == "none":
|
| 1049 |
+
# Some servers may explicitly discourage partial content requests, but
|
| 1050 |
+
# the lack of "Accept-Ranges" does not always indicate they would fail
|
| 1051 |
+
info["partial"] = False
|
| 1052 |
+
|
| 1053 |
+
info["url"] = str(r.url)
|
| 1054 |
+
|
| 1055 |
+
for checksum_field in ["ETag", "Content-MD5", "Digest", "Last-Modified"]:
|
| 1056 |
+
if r.headers.get(checksum_field):
|
| 1057 |
+
info[checksum_field] = r.headers[checksum_field]
|
| 1058 |
+
|
| 1059 |
+
return info
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
async def _file_size(url, session=None, *args, **kwargs):
|
| 1063 |
+
if session is None:
|
| 1064 |
+
session = await get_client()
|
| 1065 |
+
info = await _file_info(url, session=session, *args, **kwargs)
|
| 1066 |
+
return info.get("size")
|
| 1067 |
+
|
| 1068 |
+
|
| 1069 |
+
file_size = sync_wrapper(_file_size)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/http_sync.py
ADDED
|
@@ -0,0 +1,937 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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""
|
| 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 (
|
| 21 |
+
DEFAULT_BLOCK_SIZE,
|
| 22 |
+
isfilelike,
|
| 23 |
+
nullcontext,
|
| 24 |
+
range_response_window,
|
| 25 |
+
response_is_requested_range,
|
| 26 |
+
tokenize,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
from ..caching import AllBytes
|
| 30 |
+
|
| 31 |
+
# https://stackoverflow.com/a/15926317/3821154
|
| 32 |
+
# The attribute scan must stay linear: it stops at the next "<" or ">" and the
|
| 33 |
+
# whitespace before href is a lookbehind rather than a second quantifier, so a
|
| 34 |
+
# page cannot make it backtrack cubically (1 KB of whitespace after "<a"
|
| 35 |
+
# used to stall ls() for seconds, 10 KB for hours).
|
| 36 |
+
ex = re.compile(r"""<(a|A)\s[^<>]*?(?<=\s)(href|HREF)=["'](?P<url>[^"']+)""")
|
| 37 |
+
ex2 = re.compile(r"""(?P<url>http[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")
|
| 38 |
+
logger = logging.getLogger("fsspec.http")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class JsHttpException(urllib.error.HTTPError): ...
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class StreamIO(io.BytesIO):
|
| 45 |
+
# fake class, so you can set attributes on it
|
| 46 |
+
# will eventually actually stream
|
| 47 |
+
...
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class ResponseProxy:
|
| 51 |
+
"""Looks like a requests response"""
|
| 52 |
+
|
| 53 |
+
def __init__(self, req, stream=False):
|
| 54 |
+
self.request = req
|
| 55 |
+
self.stream = stream
|
| 56 |
+
self._data = None
|
| 57 |
+
self._headers = None
|
| 58 |
+
|
| 59 |
+
@property
|
| 60 |
+
def raw(self):
|
| 61 |
+
if self._data is None:
|
| 62 |
+
b = self.request.response.to_bytes()
|
| 63 |
+
if self.stream:
|
| 64 |
+
self._data = StreamIO(b)
|
| 65 |
+
else:
|
| 66 |
+
self._data = b
|
| 67 |
+
return self._data
|
| 68 |
+
|
| 69 |
+
def close(self):
|
| 70 |
+
if hasattr(self, "_data"):
|
| 71 |
+
del self._data
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def headers(self):
|
| 75 |
+
if self._headers is None:
|
| 76 |
+
self._headers = dict(
|
| 77 |
+
[
|
| 78 |
+
_.split(": ")
|
| 79 |
+
for _ in self.request.getAllResponseHeaders().strip().split("\r\n")
|
| 80 |
+
]
|
| 81 |
+
)
|
| 82 |
+
return self._headers
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def status_code(self):
|
| 86 |
+
return int(self.request.status)
|
| 87 |
+
|
| 88 |
+
def raise_for_status(self):
|
| 89 |
+
if not self.ok:
|
| 90 |
+
raise JsHttpException(
|
| 91 |
+
self.url, self.status_code, self.reason, self.headers, None
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def iter_content(self, chunksize, *_, **__):
|
| 95 |
+
while True:
|
| 96 |
+
out = self.raw.read(chunksize)
|
| 97 |
+
if out:
|
| 98 |
+
yield out
|
| 99 |
+
else:
|
| 100 |
+
break
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def reason(self):
|
| 104 |
+
return self.request.statusText
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def ok(self):
|
| 108 |
+
return self.status_code < 400
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def url(self):
|
| 112 |
+
return self.request.response.responseURL
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def text(self):
|
| 116 |
+
# TODO: encoding from headers
|
| 117 |
+
return self.content.decode()
|
| 118 |
+
|
| 119 |
+
@property
|
| 120 |
+
def content(self):
|
| 121 |
+
self.stream = False
|
| 122 |
+
return self.raw
|
| 123 |
+
|
| 124 |
+
def json(self):
|
| 125 |
+
return loads(self.text)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class RequestsSessionShim:
|
| 129 |
+
def __init__(self):
|
| 130 |
+
self.headers = {}
|
| 131 |
+
|
| 132 |
+
def request(
|
| 133 |
+
self,
|
| 134 |
+
method,
|
| 135 |
+
url,
|
| 136 |
+
params=None,
|
| 137 |
+
data=None,
|
| 138 |
+
headers=None,
|
| 139 |
+
cookies=None,
|
| 140 |
+
files=None,
|
| 141 |
+
auth=None,
|
| 142 |
+
timeout=None,
|
| 143 |
+
allow_redirects=None,
|
| 144 |
+
proxies=None,
|
| 145 |
+
hooks=None,
|
| 146 |
+
stream=None,
|
| 147 |
+
verify=None,
|
| 148 |
+
cert=None,
|
| 149 |
+
json=None,
|
| 150 |
+
):
|
| 151 |
+
from js import Blob, XMLHttpRequest
|
| 152 |
+
|
| 153 |
+
logger.debug("JS request: %s %s", method, url)
|
| 154 |
+
|
| 155 |
+
if cert or verify or proxies or files or cookies or hooks:
|
| 156 |
+
raise NotImplementedError
|
| 157 |
+
if data and json:
|
| 158 |
+
raise ValueError("Use json= or data=, not both")
|
| 159 |
+
req = XMLHttpRequest.new()
|
| 160 |
+
extra = auth if auth else ()
|
| 161 |
+
if params:
|
| 162 |
+
url = f"{url}?{urllib.parse.urlencode(params)}"
|
| 163 |
+
req.open(method, url, False, *extra)
|
| 164 |
+
if timeout:
|
| 165 |
+
req.timeout = timeout
|
| 166 |
+
if headers:
|
| 167 |
+
for k, v in headers.items():
|
| 168 |
+
req.setRequestHeader(k, v)
|
| 169 |
+
|
| 170 |
+
req.setRequestHeader("Accept", "application/octet-stream")
|
| 171 |
+
req.responseType = "arraybuffer"
|
| 172 |
+
if json:
|
| 173 |
+
blob = Blob.new([dumps(data)], {type: "application/json"})
|
| 174 |
+
req.send(blob)
|
| 175 |
+
elif data:
|
| 176 |
+
if isinstance(data, io.IOBase):
|
| 177 |
+
data = data.read()
|
| 178 |
+
blob = Blob.new([data], {type: "application/octet-stream"})
|
| 179 |
+
req.send(blob)
|
| 180 |
+
else:
|
| 181 |
+
req.send(None)
|
| 182 |
+
return ResponseProxy(req, stream=stream)
|
| 183 |
+
|
| 184 |
+
def get(self, url, **kwargs):
|
| 185 |
+
return self.request("GET", url, **kwargs)
|
| 186 |
+
|
| 187 |
+
def head(self, url, **kwargs):
|
| 188 |
+
return self.request("HEAD", url, **kwargs)
|
| 189 |
+
|
| 190 |
+
def post(self, url, **kwargs):
|
| 191 |
+
return self.request("POST", url, **kwargs)
|
| 192 |
+
|
| 193 |
+
def put(self, url, **kwargs):
|
| 194 |
+
return self.request("PUT", url, **kwargs)
|
| 195 |
+
|
| 196 |
+
def patch(self, url, **kwargs):
|
| 197 |
+
return self.request("PATCH", url, **kwargs)
|
| 198 |
+
|
| 199 |
+
def delete(self, url, **kwargs):
|
| 200 |
+
return self.request("DELETE", url, **kwargs)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class HTTPFileSystem(AbstractFileSystem):
|
| 204 |
+
"""
|
| 205 |
+
Simple File-System for fetching data via HTTP(S)
|
| 206 |
+
|
| 207 |
+
This is the BLOCKING version of the normal HTTPFileSystem. It uses
|
| 208 |
+
requests in normal python and the JS runtime in pyodide.
|
| 209 |
+
|
| 210 |
+
***This implementation is extremely experimental, do not use unless
|
| 211 |
+
you are testing pyodide/pyscript integration***
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
protocol = ("http", "https", "sync-http", "sync-https")
|
| 215 |
+
sep = "/"
|
| 216 |
+
|
| 217 |
+
def __init__(
|
| 218 |
+
self,
|
| 219 |
+
simple_links=True,
|
| 220 |
+
block_size=None,
|
| 221 |
+
same_scheme=True,
|
| 222 |
+
cache_type="readahead",
|
| 223 |
+
cache_options=None,
|
| 224 |
+
client_kwargs=None,
|
| 225 |
+
encoded=False,
|
| 226 |
+
**storage_options,
|
| 227 |
+
):
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
Parameters
|
| 231 |
+
----------
|
| 232 |
+
block_size: int
|
| 233 |
+
Blocks to read bytes; if 0, will default to raw requests file-like
|
| 234 |
+
objects instead of HTTPFile instances
|
| 235 |
+
simple_links: bool
|
| 236 |
+
If True, will consider both HTML <a> tags and anything that looks
|
| 237 |
+
like a URL; if False, will consider only the former.
|
| 238 |
+
same_scheme: True
|
| 239 |
+
When doing ls/glob, if this is True, only consider paths that have
|
| 240 |
+
http/https matching the input URLs.
|
| 241 |
+
size_policy: this argument is deprecated
|
| 242 |
+
client_kwargs: dict
|
| 243 |
+
Passed to aiohttp.ClientSession, see
|
| 244 |
+
https://docs.aiohttp.org/en/stable/client_reference.html
|
| 245 |
+
For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}``
|
| 246 |
+
storage_options: key-value
|
| 247 |
+
Any other parameters passed on to requests
|
| 248 |
+
cache_type, cache_options: defaults used in open
|
| 249 |
+
"""
|
| 250 |
+
super().__init__(self, **storage_options)
|
| 251 |
+
self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE
|
| 252 |
+
self.simple_links = simple_links
|
| 253 |
+
self.same_schema = same_scheme
|
| 254 |
+
self.cache_type = cache_type
|
| 255 |
+
self.cache_options = cache_options
|
| 256 |
+
self.client_kwargs = client_kwargs or {}
|
| 257 |
+
self.encoded = encoded
|
| 258 |
+
self.kwargs = storage_options
|
| 259 |
+
|
| 260 |
+
try:
|
| 261 |
+
import js # noqa: F401
|
| 262 |
+
|
| 263 |
+
logger.debug("Starting JS session")
|
| 264 |
+
self.session = RequestsSessionShim()
|
| 265 |
+
self.js = True
|
| 266 |
+
except Exception as e:
|
| 267 |
+
import requests
|
| 268 |
+
|
| 269 |
+
logger.debug("Starting cpython session because of: %s", e)
|
| 270 |
+
self.session = requests.Session(**(client_kwargs or {}))
|
| 271 |
+
self.js = False
|
| 272 |
+
|
| 273 |
+
request_options = copy(storage_options)
|
| 274 |
+
self.use_listings_cache = request_options.pop("use_listings_cache", False)
|
| 275 |
+
request_options.pop("listings_expiry_time", None)
|
| 276 |
+
request_options.pop("max_paths", None)
|
| 277 |
+
request_options.pop("skip_instance_cache", None)
|
| 278 |
+
self.kwargs = request_options
|
| 279 |
+
|
| 280 |
+
@property
|
| 281 |
+
def fsid(self):
|
| 282 |
+
return "sync-http"
|
| 283 |
+
|
| 284 |
+
def encode_url(self, url):
|
| 285 |
+
if yarl:
|
| 286 |
+
return yarl.URL(url, encoded=self.encoded)
|
| 287 |
+
return url
|
| 288 |
+
|
| 289 |
+
@classmethod
|
| 290 |
+
def _strip_protocol(cls, path: str) -> str:
|
| 291 |
+
"""For HTTP, we always want to keep the full URL"""
|
| 292 |
+
path = path.replace("sync-http://", "http://").replace(
|
| 293 |
+
"sync-https://", "https://"
|
| 294 |
+
)
|
| 295 |
+
return path
|
| 296 |
+
|
| 297 |
+
@classmethod
|
| 298 |
+
def _parent(cls, path):
|
| 299 |
+
# override, since _strip_protocol is different for URLs
|
| 300 |
+
par = super()._parent(path)
|
| 301 |
+
if len(par) > 7: # "http://..."
|
| 302 |
+
return par
|
| 303 |
+
return ""
|
| 304 |
+
|
| 305 |
+
def _ls_real(self, url, detail=True, **kwargs):
|
| 306 |
+
# ignoring URL-encoded arguments
|
| 307 |
+
kw = self.kwargs.copy()
|
| 308 |
+
kw.update(kwargs)
|
| 309 |
+
logger.debug(url)
|
| 310 |
+
r = self.session.get(self.encode_url(url), **kw)
|
| 311 |
+
self._raise_not_found_for_status(r, url)
|
| 312 |
+
text = r.text
|
| 313 |
+
if self.simple_links:
|
| 314 |
+
links = ex2.findall(text) + [u[2] for u in ex.findall(text)]
|
| 315 |
+
else:
|
| 316 |
+
links = [u[2] for u in ex.findall(text)]
|
| 317 |
+
out = set()
|
| 318 |
+
parts = urlparse(url)
|
| 319 |
+
for l in links:
|
| 320 |
+
if isinstance(l, tuple):
|
| 321 |
+
l = l[1]
|
| 322 |
+
if l.startswith("/") and len(l) > 1:
|
| 323 |
+
# absolute URL on this server
|
| 324 |
+
l = parts.scheme + "://" + parts.netloc + l
|
| 325 |
+
if l.startswith("http"):
|
| 326 |
+
if self.same_schema and l.startswith(url.rstrip("/") + "/"):
|
| 327 |
+
out.add(l)
|
| 328 |
+
elif l.replace("https", "http").startswith(
|
| 329 |
+
url.replace("https", "http").rstrip("/") + "/"
|
| 330 |
+
):
|
| 331 |
+
# allowed to cross http <-> https
|
| 332 |
+
out.add(l)
|
| 333 |
+
else:
|
| 334 |
+
if l not in ["..", "../"]:
|
| 335 |
+
# Ignore FTP-like "parent"
|
| 336 |
+
out.add("/".join([url.rstrip("/"), l.lstrip("/")]))
|
| 337 |
+
if not out and url.endswith("/"):
|
| 338 |
+
out = self._ls_real(url.rstrip("/"), detail=False, **kwargs)
|
| 339 |
+
if detail:
|
| 340 |
+
return [
|
| 341 |
+
{
|
| 342 |
+
"name": u,
|
| 343 |
+
"size": None,
|
| 344 |
+
"type": "directory" if u.endswith("/") else "file",
|
| 345 |
+
}
|
| 346 |
+
for u in out
|
| 347 |
+
]
|
| 348 |
+
else:
|
| 349 |
+
return sorted(out)
|
| 350 |
+
|
| 351 |
+
def ls(self, url, detail=True, **kwargs):
|
| 352 |
+
if self.use_listings_cache and url in self.dircache:
|
| 353 |
+
out = self.dircache[url]
|
| 354 |
+
else:
|
| 355 |
+
out = self._ls_real(url, detail=True, **kwargs)
|
| 356 |
+
self.dircache[url] = out
|
| 357 |
+
if detail:
|
| 358 |
+
return out
|
| 359 |
+
return sorted(entry["name"] for entry in out)
|
| 360 |
+
|
| 361 |
+
def _raise_not_found_for_status(self, response, url):
|
| 362 |
+
"""
|
| 363 |
+
Raises FileNotFoundError for 404s, otherwise uses raise_for_status.
|
| 364 |
+
"""
|
| 365 |
+
if response.status_code == 404:
|
| 366 |
+
raise FileNotFoundError(url)
|
| 367 |
+
response.raise_for_status()
|
| 368 |
+
|
| 369 |
+
def cat_file(self, url, start=None, end=None, **kwargs):
|
| 370 |
+
kw = self.kwargs.copy()
|
| 371 |
+
kw.update(kwargs)
|
| 372 |
+
logger.debug(url)
|
| 373 |
+
|
| 374 |
+
ranged = start is not None or end is not None
|
| 375 |
+
if ranged:
|
| 376 |
+
if start == end or (start is None and end == 0):
|
| 377 |
+
return b""
|
| 378 |
+
headers = kw.pop("headers", {}).copy()
|
| 379 |
+
|
| 380 |
+
headers["Range"] = self._process_limits(url, start, end)
|
| 381 |
+
kw["headers"] = headers
|
| 382 |
+
r = self.session.get(self.encode_url(url), **kw)
|
| 383 |
+
self._raise_not_found_for_status(r, url)
|
| 384 |
+
if not ranged:
|
| 385 |
+
return r.content
|
| 386 |
+
# a server that ignores the Range header replies with the whole file,
|
| 387 |
+
# which is not the window the caller asked for
|
| 388 |
+
return range_response_window(r.content, r.status_code, r.headers, start, end)
|
| 389 |
+
|
| 390 |
+
def get_file(
|
| 391 |
+
self, rpath, lpath, chunk_size=5 * 2**20, callback=_DEFAULT_CALLBACK, **kwargs
|
| 392 |
+
):
|
| 393 |
+
kw = self.kwargs.copy()
|
| 394 |
+
kw.update(kwargs)
|
| 395 |
+
logger.debug(rpath)
|
| 396 |
+
r = self.session.get(self.encode_url(rpath), **kw)
|
| 397 |
+
try:
|
| 398 |
+
size = int(
|
| 399 |
+
r.headers.get("content-length", None)
|
| 400 |
+
or r.headers.get("Content-Length", None)
|
| 401 |
+
)
|
| 402 |
+
except (ValueError, KeyError, TypeError):
|
| 403 |
+
size = None
|
| 404 |
+
|
| 405 |
+
callback.set_size(size)
|
| 406 |
+
self._raise_not_found_for_status(r, rpath)
|
| 407 |
+
context = nullcontext(lpath) if isfilelike(lpath) else open(lpath, "wb")
|
| 408 |
+
with context as outfile:
|
| 409 |
+
for chunk in r.iter_content(chunk_size, decode_unicode=False):
|
| 410 |
+
outfile.write(chunk)
|
| 411 |
+
callback.relative_update(len(chunk))
|
| 412 |
+
|
| 413 |
+
def put_file(
|
| 414 |
+
self,
|
| 415 |
+
lpath,
|
| 416 |
+
rpath,
|
| 417 |
+
chunk_size=5 * 2**20,
|
| 418 |
+
callback=_DEFAULT_CALLBACK,
|
| 419 |
+
method="post",
|
| 420 |
+
**kwargs,
|
| 421 |
+
):
|
| 422 |
+
def gen_chunks():
|
| 423 |
+
# Support passing arbitrary file-like objects
|
| 424 |
+
# and use them instead of streams.
|
| 425 |
+
if isinstance(lpath, io.IOBase):
|
| 426 |
+
context = nullcontext(lpath)
|
| 427 |
+
use_seek = False # might not support seeking
|
| 428 |
+
else:
|
| 429 |
+
context = open(lpath, "rb")
|
| 430 |
+
use_seek = True
|
| 431 |
+
|
| 432 |
+
with context as f:
|
| 433 |
+
if use_seek:
|
| 434 |
+
callback.set_size(f.seek(0, 2))
|
| 435 |
+
f.seek(0)
|
| 436 |
+
else:
|
| 437 |
+
callback.set_size(getattr(f, "size", None))
|
| 438 |
+
|
| 439 |
+
chunk = f.read(chunk_size)
|
| 440 |
+
while chunk:
|
| 441 |
+
yield chunk
|
| 442 |
+
callback.relative_update(len(chunk))
|
| 443 |
+
chunk = f.read(chunk_size)
|
| 444 |
+
|
| 445 |
+
kw = self.kwargs.copy()
|
| 446 |
+
kw.update(kwargs)
|
| 447 |
+
|
| 448 |
+
method = method.lower()
|
| 449 |
+
if method not in ("post", "put"):
|
| 450 |
+
raise ValueError(
|
| 451 |
+
f"method has to be either 'post' or 'put', not: {method!r}"
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
meth = getattr(self.session, method)
|
| 455 |
+
resp = meth(rpath, data=gen_chunks(), **kw)
|
| 456 |
+
self._raise_not_found_for_status(resp, rpath)
|
| 457 |
+
|
| 458 |
+
def _process_limits(self, url, start, end):
|
| 459 |
+
"""Helper for "Range"-based _cat_file"""
|
| 460 |
+
size = None
|
| 461 |
+
suff = False
|
| 462 |
+
if start is not None and start < 0:
|
| 463 |
+
# if start is negative and end None, end is the "suffix length"
|
| 464 |
+
if end is None:
|
| 465 |
+
end = -start
|
| 466 |
+
start = ""
|
| 467 |
+
suff = True
|
| 468 |
+
else:
|
| 469 |
+
size = size or self.info(url)["size"]
|
| 470 |
+
start = size + start
|
| 471 |
+
elif start is None:
|
| 472 |
+
start = 0
|
| 473 |
+
if not suff:
|
| 474 |
+
if end is not None and end < 0:
|
| 475 |
+
if start is not None:
|
| 476 |
+
size = size or self.info(url)["size"]
|
| 477 |
+
end = size + end
|
| 478 |
+
elif end is None:
|
| 479 |
+
end = ""
|
| 480 |
+
if isinstance(end, int):
|
| 481 |
+
end -= 1 # bytes range is inclusive
|
| 482 |
+
return f"bytes={start}-{end}"
|
| 483 |
+
|
| 484 |
+
def exists(self, path, strict=False, **kwargs):
|
| 485 |
+
kw = self.kwargs.copy()
|
| 486 |
+
kw.update(kwargs)
|
| 487 |
+
try:
|
| 488 |
+
logger.debug(path)
|
| 489 |
+
r = self.session.get(self.encode_url(path), **kw)
|
| 490 |
+
if strict:
|
| 491 |
+
self._raise_not_found_for_status(r, path)
|
| 492 |
+
return r.status_code < 400
|
| 493 |
+
except FileNotFoundError:
|
| 494 |
+
return False
|
| 495 |
+
except Exception:
|
| 496 |
+
if strict:
|
| 497 |
+
raise
|
| 498 |
+
return False
|
| 499 |
+
|
| 500 |
+
def isfile(self, path, **kwargs):
|
| 501 |
+
return self.exists(path, **kwargs)
|
| 502 |
+
|
| 503 |
+
def _open(
|
| 504 |
+
self,
|
| 505 |
+
path,
|
| 506 |
+
mode="rb",
|
| 507 |
+
block_size=None,
|
| 508 |
+
autocommit=None, # XXX: This differs from the base class.
|
| 509 |
+
cache_type=None,
|
| 510 |
+
cache_options=None,
|
| 511 |
+
size=None,
|
| 512 |
+
**kwargs,
|
| 513 |
+
):
|
| 514 |
+
"""Make a file-like object
|
| 515 |
+
|
| 516 |
+
Parameters
|
| 517 |
+
----------
|
| 518 |
+
path: str
|
| 519 |
+
Full URL with protocol
|
| 520 |
+
mode: string
|
| 521 |
+
must be "rb"
|
| 522 |
+
block_size: int or None
|
| 523 |
+
Bytes to download in one request; use instance value if None. If
|
| 524 |
+
zero, will return a streaming Requests file-like instance.
|
| 525 |
+
kwargs: key-value
|
| 526 |
+
Any other parameters, passed to requests calls
|
| 527 |
+
"""
|
| 528 |
+
if mode != "rb":
|
| 529 |
+
raise NotImplementedError
|
| 530 |
+
block_size = block_size if block_size is not None else self.block_size
|
| 531 |
+
kw = self.kwargs.copy()
|
| 532 |
+
kw.update(kwargs)
|
| 533 |
+
size = size or self.info(path, **kwargs)["size"]
|
| 534 |
+
if block_size and size:
|
| 535 |
+
return HTTPFile(
|
| 536 |
+
self,
|
| 537 |
+
path,
|
| 538 |
+
session=self.session,
|
| 539 |
+
block_size=block_size,
|
| 540 |
+
mode=mode,
|
| 541 |
+
size=size,
|
| 542 |
+
cache_type=cache_type or self.cache_type,
|
| 543 |
+
cache_options=cache_options or self.cache_options,
|
| 544 |
+
**kw,
|
| 545 |
+
)
|
| 546 |
+
else:
|
| 547 |
+
return HTTPStreamFile(
|
| 548 |
+
self,
|
| 549 |
+
path,
|
| 550 |
+
mode=mode,
|
| 551 |
+
session=self.session,
|
| 552 |
+
**kw,
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
def ukey(self, url):
|
| 556 |
+
"""Unique identifier; assume HTTP files are static, unchanging"""
|
| 557 |
+
return tokenize(url, self.kwargs, self.protocol)
|
| 558 |
+
|
| 559 |
+
def info(self, url, **kwargs):
|
| 560 |
+
"""Get info of URL
|
| 561 |
+
|
| 562 |
+
Tries to access location via HEAD, and then GET methods, but does
|
| 563 |
+
not fetch the data.
|
| 564 |
+
|
| 565 |
+
It is possible that the server does not supply any size information, in
|
| 566 |
+
which case size will be given as None (and certain operations on the
|
| 567 |
+
corresponding file will not work).
|
| 568 |
+
"""
|
| 569 |
+
info = {}
|
| 570 |
+
for policy in ["head", "get"]:
|
| 571 |
+
try:
|
| 572 |
+
info.update(
|
| 573 |
+
_file_info(
|
| 574 |
+
self.encode_url(url),
|
| 575 |
+
size_policy=policy,
|
| 576 |
+
session=self.session,
|
| 577 |
+
**self.kwargs,
|
| 578 |
+
**kwargs,
|
| 579 |
+
)
|
| 580 |
+
)
|
| 581 |
+
if info.get("size") is not None:
|
| 582 |
+
break
|
| 583 |
+
except Exception as exc:
|
| 584 |
+
if policy == "get":
|
| 585 |
+
# If get failed, then raise a FileNotFoundError
|
| 586 |
+
raise FileNotFoundError(url) from exc
|
| 587 |
+
logger.debug(str(exc))
|
| 588 |
+
|
| 589 |
+
return {"name": url, "size": None, **info, "type": "file"}
|
| 590 |
+
|
| 591 |
+
def glob(self, path, maxdepth=None, **kwargs):
|
| 592 |
+
"""
|
| 593 |
+
Find files by glob-matching.
|
| 594 |
+
|
| 595 |
+
This implementation is idntical to the one in AbstractFileSystem,
|
| 596 |
+
but "?" is not considered as a character for globbing, because it is
|
| 597 |
+
so common in URLs, often identifying the "query" part.
|
| 598 |
+
"""
|
| 599 |
+
import re
|
| 600 |
+
|
| 601 |
+
ends = path.endswith("/")
|
| 602 |
+
path = self._strip_protocol(path)
|
| 603 |
+
indstar = path.find("*") if path.find("*") >= 0 else len(path)
|
| 604 |
+
indbrace = path.find("[") if path.find("[") >= 0 else len(path)
|
| 605 |
+
|
| 606 |
+
ind = min(indstar, indbrace)
|
| 607 |
+
|
| 608 |
+
detail = kwargs.pop("detail", False)
|
| 609 |
+
|
| 610 |
+
if not has_magic(path):
|
| 611 |
+
root = path
|
| 612 |
+
depth = 1
|
| 613 |
+
if ends:
|
| 614 |
+
path += "/*"
|
| 615 |
+
elif self.exists(path):
|
| 616 |
+
if not detail:
|
| 617 |
+
return [path]
|
| 618 |
+
else:
|
| 619 |
+
return {path: self.info(path)}
|
| 620 |
+
else:
|
| 621 |
+
if not detail:
|
| 622 |
+
return [] # glob of non-existent returns empty
|
| 623 |
+
else:
|
| 624 |
+
return {}
|
| 625 |
+
elif "/" in path[:ind]:
|
| 626 |
+
ind2 = path[:ind].rindex("/")
|
| 627 |
+
root = path[: ind2 + 1]
|
| 628 |
+
depth = None if "**" in path else path[ind2 + 1 :].count("/") + 1
|
| 629 |
+
else:
|
| 630 |
+
root = ""
|
| 631 |
+
depth = None if "**" in path else path[ind + 1 :].count("/") + 1
|
| 632 |
+
|
| 633 |
+
allpaths = self.find(
|
| 634 |
+
root, maxdepth=maxdepth or depth, withdirs=True, detail=True, **kwargs
|
| 635 |
+
)
|
| 636 |
+
# Escape characters special to python regex, leaving our supported
|
| 637 |
+
# special characters in place.
|
| 638 |
+
# See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
|
| 639 |
+
# for shell globbing details.
|
| 640 |
+
pattern = (
|
| 641 |
+
"^"
|
| 642 |
+
+ (
|
| 643 |
+
path.replace("\\", r"\\")
|
| 644 |
+
.replace(".", r"\.")
|
| 645 |
+
.replace("+", r"\+")
|
| 646 |
+
.replace("//", "/")
|
| 647 |
+
.replace("(", r"\(")
|
| 648 |
+
.replace(")", r"\)")
|
| 649 |
+
.replace("|", r"\|")
|
| 650 |
+
.replace("^", r"\^")
|
| 651 |
+
.replace("$", r"\$")
|
| 652 |
+
.replace("{", r"\{")
|
| 653 |
+
.replace("}", r"\}")
|
| 654 |
+
.rstrip("/")
|
| 655 |
+
)
|
| 656 |
+
+ "$"
|
| 657 |
+
)
|
| 658 |
+
pattern = re.sub("[*]{2}", "=PLACEHOLDER=", pattern)
|
| 659 |
+
pattern = re.sub("[*]", "[^/]*", pattern)
|
| 660 |
+
pattern = re.compile(pattern.replace("=PLACEHOLDER=", ".*"))
|
| 661 |
+
out = {
|
| 662 |
+
p: allpaths[p]
|
| 663 |
+
for p in sorted(allpaths)
|
| 664 |
+
if pattern.match(p.replace("//", "/").rstrip("/"))
|
| 665 |
+
}
|
| 666 |
+
if detail:
|
| 667 |
+
return out
|
| 668 |
+
else:
|
| 669 |
+
return list(out)
|
| 670 |
+
|
| 671 |
+
def isdir(self, path):
|
| 672 |
+
# override, since all URLs are (also) files
|
| 673 |
+
try:
|
| 674 |
+
return bool(self.ls(path))
|
| 675 |
+
except (FileNotFoundError, ValueError):
|
| 676 |
+
return False
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
class HTTPFile(AbstractBufferedFile):
|
| 680 |
+
"""
|
| 681 |
+
A file-like object pointing to a remove HTTP(S) resource
|
| 682 |
+
|
| 683 |
+
Supports only reading, with read-ahead of a predermined block-size.
|
| 684 |
+
|
| 685 |
+
In the case that the server does not supply the filesize, only reading of
|
| 686 |
+
the complete file in one go is supported.
|
| 687 |
+
|
| 688 |
+
Parameters
|
| 689 |
+
----------
|
| 690 |
+
url: str
|
| 691 |
+
Full URL of the remote resource, including the protocol
|
| 692 |
+
session: requests.Session or None
|
| 693 |
+
All calls will be made within this session, to avoid restarting
|
| 694 |
+
connections where the server allows this
|
| 695 |
+
block_size: int or None
|
| 696 |
+
The amount of read-ahead to do, in bytes. Default is 5MB, or the value
|
| 697 |
+
configured for the FileSystem creating this file
|
| 698 |
+
size: None or int
|
| 699 |
+
If given, this is the size of the file in bytes, and we don't attempt
|
| 700 |
+
to call the server to find the value.
|
| 701 |
+
kwargs: all other key-values are passed to requests calls.
|
| 702 |
+
"""
|
| 703 |
+
|
| 704 |
+
def __init__(
|
| 705 |
+
self,
|
| 706 |
+
fs,
|
| 707 |
+
url,
|
| 708 |
+
session=None,
|
| 709 |
+
block_size=None,
|
| 710 |
+
mode="rb",
|
| 711 |
+
cache_type="bytes",
|
| 712 |
+
cache_options=None,
|
| 713 |
+
size=None,
|
| 714 |
+
**kwargs,
|
| 715 |
+
):
|
| 716 |
+
if mode != "rb":
|
| 717 |
+
raise NotImplementedError("File mode not supported")
|
| 718 |
+
self.url = url
|
| 719 |
+
self.session = session
|
| 720 |
+
self.details = {"name": url, "size": size, "type": "file"}
|
| 721 |
+
super().__init__(
|
| 722 |
+
fs=fs,
|
| 723 |
+
path=url,
|
| 724 |
+
mode=mode,
|
| 725 |
+
block_size=block_size,
|
| 726 |
+
cache_type=cache_type,
|
| 727 |
+
cache_options=cache_options,
|
| 728 |
+
**kwargs,
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
def read(self, length=-1):
|
| 732 |
+
"""Read bytes from file
|
| 733 |
+
|
| 734 |
+
Parameters
|
| 735 |
+
----------
|
| 736 |
+
length: int
|
| 737 |
+
Read up to this many bytes. If negative, read all content to end of
|
| 738 |
+
file. If the server has not supplied the filesize, attempting to
|
| 739 |
+
read only part of the data will raise a ValueError.
|
| 740 |
+
"""
|
| 741 |
+
if (
|
| 742 |
+
(length < 0 and self.loc == 0) # explicit read all
|
| 743 |
+
# but not when the size is known and fits into a block anyways
|
| 744 |
+
and not (self.size is not None and self.size <= self.blocksize)
|
| 745 |
+
):
|
| 746 |
+
self._fetch_all()
|
| 747 |
+
if self.size is None:
|
| 748 |
+
if length < 0:
|
| 749 |
+
self._fetch_all()
|
| 750 |
+
else:
|
| 751 |
+
length = min(self.size - self.loc, length)
|
| 752 |
+
return super().read(length)
|
| 753 |
+
|
| 754 |
+
def _fetch_all(self):
|
| 755 |
+
"""Read whole file in one shot, without caching
|
| 756 |
+
|
| 757 |
+
This is only called when position is still at zero,
|
| 758 |
+
and read() is called without a byte-count.
|
| 759 |
+
"""
|
| 760 |
+
logger.debug(f"Fetch all for {self}")
|
| 761 |
+
if not isinstance(self.cache, AllBytes):
|
| 762 |
+
r = self.session.get(self.fs.encode_url(self.url), **self.kwargs)
|
| 763 |
+
r.raise_for_status()
|
| 764 |
+
out = r.content
|
| 765 |
+
self.cache = AllBytes(size=len(out), fetcher=None, blocksize=None, data=out)
|
| 766 |
+
self.size = len(out)
|
| 767 |
+
|
| 768 |
+
def _fetch_range(self, start, end):
|
| 769 |
+
"""Download a block of data
|
| 770 |
+
|
| 771 |
+
The expectation is that the server returns only the requested bytes,
|
| 772 |
+
with HTTP code 206. If this is not the case, we first check the headers,
|
| 773 |
+
and then stream the output - if the data size is bigger than we
|
| 774 |
+
requested, an exception is raised.
|
| 775 |
+
"""
|
| 776 |
+
logger.debug(f"Fetch range for {self}: {start}-{end}")
|
| 777 |
+
kwargs = self.kwargs.copy()
|
| 778 |
+
headers = kwargs.pop("headers", {}).copy()
|
| 779 |
+
headers["Range"] = f"bytes={start}-{end - 1}"
|
| 780 |
+
logger.debug("%s : %s", self.url, headers["Range"])
|
| 781 |
+
r = self.session.get(self.fs.encode_url(self.url), headers=headers, **kwargs)
|
| 782 |
+
if r.status_code == 416:
|
| 783 |
+
# range request outside file
|
| 784 |
+
return b""
|
| 785 |
+
r.raise_for_status()
|
| 786 |
+
|
| 787 |
+
# If the server has handled the range request, it should reply
|
| 788 |
+
# with status 206 (partial content). But we'll guess that a suitable
|
| 789 |
+
# Content-Range header or a Content-Length no more than the
|
| 790 |
+
# requested range also mean we have got the desired range.
|
| 791 |
+
if response_is_requested_range(r.status_code, r.headers, start, end):
|
| 792 |
+
# partial content, as expected
|
| 793 |
+
out = r.content
|
| 794 |
+
elif start > 0:
|
| 795 |
+
raise ValueError(
|
| 796 |
+
"The HTTP server doesn't appear to support range requests. "
|
| 797 |
+
"Only reading this file from the beginning is supported. "
|
| 798 |
+
"Open with block_size=0 for a streaming file interface."
|
| 799 |
+
)
|
| 800 |
+
else:
|
| 801 |
+
# Response is not a range, but we want the start of the file,
|
| 802 |
+
# so we can read the required amount anyway.
|
| 803 |
+
cl = 0
|
| 804 |
+
out = []
|
| 805 |
+
for chunk in r.iter_content(2**20, False):
|
| 806 |
+
out.append(chunk)
|
| 807 |
+
cl += len(chunk)
|
| 808 |
+
out = b"".join(out)[: end - start]
|
| 809 |
+
return out
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
magic_check = re.compile("([*[])")
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def has_magic(s):
|
| 816 |
+
match = magic_check.search(s)
|
| 817 |
+
return match is not None
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
class HTTPStreamFile(AbstractBufferedFile):
|
| 821 |
+
def __init__(self, fs, url, mode="rb", session=None, **kwargs):
|
| 822 |
+
self.url = url
|
| 823 |
+
self.session = session
|
| 824 |
+
if mode != "rb":
|
| 825 |
+
raise ValueError
|
| 826 |
+
self.details = {"name": url, "size": None}
|
| 827 |
+
super().__init__(fs=fs, path=url, mode=mode, cache_type="readahead", **kwargs)
|
| 828 |
+
|
| 829 |
+
r = self.session.get(self.fs.encode_url(url), stream=True, **kwargs)
|
| 830 |
+
self.fs._raise_not_found_for_status(r, url)
|
| 831 |
+
self.it = r.iter_content(1024, False)
|
| 832 |
+
self.leftover = b""
|
| 833 |
+
|
| 834 |
+
self.r = r
|
| 835 |
+
|
| 836 |
+
def seek(self, *args, **kwargs):
|
| 837 |
+
raise ValueError("Cannot seek streaming HTTP file")
|
| 838 |
+
|
| 839 |
+
def read(self, num=-1):
|
| 840 |
+
bufs = [self.leftover]
|
| 841 |
+
leng = len(self.leftover)
|
| 842 |
+
while leng < num or num < 0:
|
| 843 |
+
try:
|
| 844 |
+
out = self.it.__next__()
|
| 845 |
+
except StopIteration:
|
| 846 |
+
break
|
| 847 |
+
if out:
|
| 848 |
+
bufs.append(out)
|
| 849 |
+
else:
|
| 850 |
+
break
|
| 851 |
+
leng += len(out)
|
| 852 |
+
out = b"".join(bufs)
|
| 853 |
+
if num >= 0:
|
| 854 |
+
self.leftover = out[num:]
|
| 855 |
+
out = out[:num]
|
| 856 |
+
else:
|
| 857 |
+
self.leftover = b""
|
| 858 |
+
self.loc += len(out)
|
| 859 |
+
return out
|
| 860 |
+
|
| 861 |
+
def close(self):
|
| 862 |
+
self.r.close()
|
| 863 |
+
self.closed = True
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
def get_range(session, url, start, end, **kwargs):
|
| 867 |
+
# explicit get a range when we know it must be safe
|
| 868 |
+
kwargs = kwargs.copy()
|
| 869 |
+
headers = kwargs.pop("headers", {}).copy()
|
| 870 |
+
headers["Range"] = f"bytes={start}-{end - 1}"
|
| 871 |
+
r = session.get(url, headers=headers, **kwargs)
|
| 872 |
+
r.raise_for_status()
|
| 873 |
+
return r.content
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
def _file_info(url, session, size_policy="head", **kwargs):
|
| 877 |
+
"""Call HEAD on the server to get details about the file (size/checksum etc.)
|
| 878 |
+
|
| 879 |
+
Default operation is to explicitly allow redirects and use encoding
|
| 880 |
+
'identity' (no compression) to get the true size of the target.
|
| 881 |
+
"""
|
| 882 |
+
logger.debug("Retrieve file size for %s", url)
|
| 883 |
+
kwargs = kwargs.copy()
|
| 884 |
+
ar = kwargs.pop("allow_redirects", True)
|
| 885 |
+
head = kwargs.get("headers", {}).copy()
|
| 886 |
+
# TODO: not allowed in JS
|
| 887 |
+
# head["Accept-Encoding"] = "identity"
|
| 888 |
+
kwargs["headers"] = head
|
| 889 |
+
|
| 890 |
+
info = {}
|
| 891 |
+
if size_policy == "head":
|
| 892 |
+
r = session.head(url, allow_redirects=ar, **kwargs)
|
| 893 |
+
elif size_policy == "get":
|
| 894 |
+
r = session.get(url, allow_redirects=ar, **kwargs)
|
| 895 |
+
else:
|
| 896 |
+
raise TypeError(f'size_policy must be "head" or "get", got {size_policy}')
|
| 897 |
+
r.raise_for_status()
|
| 898 |
+
|
| 899 |
+
# TODO:
|
| 900 |
+
# recognise lack of 'Accept-Ranges',
|
| 901 |
+
# or 'Accept-Ranges': 'none' (not 'bytes')
|
| 902 |
+
# to mean streaming only, no random access => return None
|
| 903 |
+
encoding = r.headers.get("Content-Encoding", r.headers.get("content-encoding", ""))
|
| 904 |
+
# The transport length is not the size of the decoded stream.
|
| 905 |
+
if encoding in ("identity", ""):
|
| 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)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/ia.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
| 1 |
+
"""Files in Internet Archive items, ``ia://<item>/<filename>``."""
|
| 2 |
+
|
| 3 |
+
import configparser
|
| 4 |
+
import os
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
import aiohttp
|
| 8 |
+
from aiohttp import hdrs
|
| 9 |
+
|
| 10 |
+
from ..utils import stringify_path
|
| 11 |
+
from .http import HTTPFileSystem
|
| 12 |
+
|
| 13 |
+
DOWNLOAD_URL = "https://archive.org/download/"
|
| 14 |
+
AUTH_DOMAIN = ".archive.org"
|
| 15 |
+
# The environment variable names the ``internetarchive`` package uses.
|
| 16 |
+
ENV_ACCESS_KEY = "IA_ACCESS_KEY_ID"
|
| 17 |
+
ENV_SECRET_KEY = "IA_SECRET_ACCESS_KEY"
|
| 18 |
+
ENV_CONFIG_FILE = "IA_CONFIG_FILE"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def ia_config_path():
|
| 22 |
+
"""The ``ia.ini`` written by ``ia configure``, or None.
|
| 23 |
+
|
| 24 |
+
Searched the way the ``internetarchive`` package searches: ``$IA_CONFIG_FILE``,
|
| 25 |
+
``$XDG_CONFIG_HOME/internetarchive/ia.ini`` (``XDG_CONFIG_HOME`` defaulting to
|
| 26 |
+
``~/.config``), ``~/.config/ia.ini``, ``~/.ia``. The first existing file wins.
|
| 27 |
+
"""
|
| 28 |
+
home = os.path.expanduser("~")
|
| 29 |
+
xdg = os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config")
|
| 30 |
+
candidates = [
|
| 31 |
+
os.environ.get(ENV_CONFIG_FILE),
|
| 32 |
+
os.path.join(xdg, "internetarchive", "ia.ini"),
|
| 33 |
+
os.path.join(home, ".config", "ia.ini"),
|
| 34 |
+
os.path.join(home, ".ia"),
|
| 35 |
+
]
|
| 36 |
+
return next((p for p in candidates if p and os.path.isfile(p)), None)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@dataclass(frozen=True)
|
| 40 |
+
class IACredentials:
|
| 41 |
+
"""The IA-S3 key pair that logs a request in at archive.org; None means anonymous."""
|
| 42 |
+
|
| 43 |
+
access_key: "str | None" = None
|
| 44 |
+
secret_key: "str | None" = None
|
| 45 |
+
config_file: "str | None" = None # where they were read from
|
| 46 |
+
|
| 47 |
+
@property
|
| 48 |
+
def anonymous(self):
|
| 49 |
+
return not self.access_key
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def authorization(self):
|
| 53 |
+
"""The ``Authorization`` header value, or None when anonymous."""
|
| 54 |
+
if self.anonymous:
|
| 55 |
+
return None
|
| 56 |
+
return f"LOW {self.access_key}:{self.secret_key}"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def load_ia_credentials(config_file=None):
|
| 60 |
+
"""Credentials from ``ia.ini`` and the environment; anonymous when there are none.
|
| 61 |
+
|
| 62 |
+
``[s3] access/secret`` are read from ``config_file`` (default:
|
| 63 |
+
:func:`ia_config_path`); the ``[cookies]`` section ``ia configure`` also writes is
|
| 64 |
+
ignored, as the keys log a request in on their own. ``IA_ACCESS_KEY_ID`` /
|
| 65 |
+
``IA_SECRET_ACCESS_KEY`` override the file's keys and must be set together. A
|
| 66 |
+
missing file or section is not an error: public items need nothing.
|
| 67 |
+
"""
|
| 68 |
+
path = config_file or ia_config_path()
|
| 69 |
+
access_key = secret_key = None
|
| 70 |
+
if path and os.path.isfile(path):
|
| 71 |
+
# RawConfigParser: the file's cookie values contain '%' (URL-encoded
|
| 72 |
+
# emails), which the default interpolation would reject.
|
| 73 |
+
parser = configparser.RawConfigParser()
|
| 74 |
+
parser.read(path, encoding="utf-8")
|
| 75 |
+
access_key = parser.get("s3", "access", fallback="").strip() or None
|
| 76 |
+
secret_key = parser.get("s3", "secret", fallback="").strip() or None
|
| 77 |
+
|
| 78 |
+
env_access = os.environ.get(ENV_ACCESS_KEY)
|
| 79 |
+
env_secret = os.environ.get(ENV_SECRET_KEY)
|
| 80 |
+
if bool(env_access) != bool(env_secret):
|
| 81 |
+
raise ValueError(f"{ENV_ACCESS_KEY} and {ENV_SECRET_KEY} must be set together")
|
| 82 |
+
if env_access:
|
| 83 |
+
access_key, secret_key = env_access, env_secret
|
| 84 |
+
if not (access_key and secret_key):
|
| 85 |
+
access_key = secret_key = None
|
| 86 |
+
found = path if path and os.path.isfile(path) else None
|
| 87 |
+
return IACredentials(access_key, secret_key, found)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def in_domain(host, domain):
|
| 91 |
+
"""Whether ``host`` is ``domain`` (leading dot optional) or a subdomain of it."""
|
| 92 |
+
if not host:
|
| 93 |
+
return False
|
| 94 |
+
domain = domain.lower().lstrip(".")
|
| 95 |
+
host = host.lower().rstrip(".")
|
| 96 |
+
return host == domain or host.endswith("." + domain)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def authorized_request_class(
|
| 100 |
+
authorization, domain, base=aiohttp.ClientRequest, https_only=True
|
| 101 |
+
):
|
| 102 |
+
"""A ``ClientRequest`` that sends ``authorization`` to every host in ``domain``.
|
| 103 |
+
|
| 104 |
+
aiohttp drops ``Authorization`` when a redirect changes origin, and every
|
| 105 |
+
archive.org download is such a redirect (to a data node). It builds a new
|
| 106 |
+
request from the session's ``request_class`` for each hop, so setting the header
|
| 107 |
+
here puts it back on the data-node hop; testing the host keeps it from leaving
|
| 108 |
+
``domain`` should a data node redirect elsewhere. With ``https_only``, a plain
|
| 109 |
+
http hop gets no header either, as aiohttp would also have dropped it on an
|
| 110 |
+
https -> http redirect.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
class AuthorizedRequest(base):
|
| 114 |
+
def update_headers(self, headers):
|
| 115 |
+
super().update_headers(headers)
|
| 116 |
+
if https_only and self.url.scheme != "https":
|
| 117 |
+
return
|
| 118 |
+
if in_domain(self.url.host, domain):
|
| 119 |
+
self.headers[hdrs.AUTHORIZATION] = authorization
|
| 120 |
+
|
| 121 |
+
return AuthorizedRequest
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class InternetArchiveFileSystem(HTTPFileSystem):
|
| 125 |
+
"""Files in Internet Archive items, addressed as ``ia://<item>/<filename>``.
|
| 126 |
+
|
| 127 |
+
Every path is read from ``https://archive.org/download/<item>/<filename>``,
|
| 128 |
+
which redirects to a data node that honours HTTP Range requests, so this is
|
| 129 |
+
``HTTPFileSystem`` with a path mapping and archive.org credentials. (IA's
|
| 130 |
+
S3-like API at ``s3.us.archive.org`` is not used: it ignores Range headers and
|
| 131 |
+
redirects GET to plain-http data nodes, so block reads would fetch whole files.)
|
| 132 |
+
|
| 133 |
+
Public items need no credentials. Restricted items need the account's IA-S3
|
| 134 |
+
keys, as written by ``ia configure`` from the ``internetarchive`` package to
|
| 135 |
+
``ia.ini``; that file is found the way the package finds it (``$IA_CONFIG_FILE``,
|
| 136 |
+
``$XDG_CONFIG_HOME/internetarchive/ia.ini``, ``~/.config/ia.ini``, ``~/.ia``).
|
| 137 |
+
Explicit arguments win over the file.
|
| 138 |
+
|
| 139 |
+
Parameters
|
| 140 |
+
----------
|
| 141 |
+
access_key, secret_key: str, optional
|
| 142 |
+
IA S3 keys, sent as ``Authorization: LOW <access>:<secret>`` to every
|
| 143 |
+
archive.org host, including the data node the download URL redirects to
|
| 144 |
+
(aiohttp drops the header on a cross-origin redirect; the session's request
|
| 145 |
+
class puts it back, and only for ``.archive.org`` hosts over https). Both
|
| 146 |
+
or neither; ``IA_ACCESS_KEY_ID`` / ``IA_SECRET_ACCESS_KEY`` in the
|
| 147 |
+
environment override ``ia.ini``. Pass empty strings to stay anonymous
|
| 148 |
+
despite an ``ia.ini``.
|
| 149 |
+
config_file: str, optional
|
| 150 |
+
Path to an ``ia.ini`` to read credentials from instead of the default lookup.
|
| 151 |
+
kwargs:
|
| 152 |
+
Passed to ``HTTPFileSystem``.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
protocol = "ia"
|
| 156 |
+
download_url = DOWNLOAD_URL
|
| 157 |
+
auth_domain = AUTH_DOMAIN
|
| 158 |
+
|
| 159 |
+
def __init__(self, access_key=None, secret_key=None, config_file=None, **kwargs):
|
| 160 |
+
if access_key is None and secret_key is None:
|
| 161 |
+
found = load_ia_credentials(config_file)
|
| 162 |
+
access_key, secret_key = found.access_key, found.secret_key
|
| 163 |
+
elif bool(access_key) != bool(secret_key):
|
| 164 |
+
raise ValueError("access_key and secret_key must be given together")
|
| 165 |
+
credentials = IACredentials(access_key or None, secret_key or None)
|
| 166 |
+
self.access_key = credentials.access_key
|
| 167 |
+
self.authorization = credentials.authorization
|
| 168 |
+
if self.authorization:
|
| 169 |
+
client_kwargs = dict(kwargs.pop("client_kwargs", None) or {})
|
| 170 |
+
client_kwargs["request_class"] = authorized_request_class(
|
| 171 |
+
self.authorization,
|
| 172 |
+
self.auth_domain,
|
| 173 |
+
client_kwargs.get("request_class", aiohttp.ClientRequest),
|
| 174 |
+
https_only=self.download_url.startswith("https://"),
|
| 175 |
+
)
|
| 176 |
+
kwargs["client_kwargs"] = client_kwargs
|
| 177 |
+
super().__init__(**kwargs)
|
| 178 |
+
|
| 179 |
+
@property
|
| 180 |
+
def fsid(self):
|
| 181 |
+
return "ia"
|
| 182 |
+
|
| 183 |
+
@classmethod
|
| 184 |
+
def _strip_protocol(cls, path):
|
| 185 |
+
"""``ia://item/file`` (or bare ``item/file``) becomes the download URL.
|
| 186 |
+
|
| 187 |
+
A URL passes through unchanged, so the mapping is idempotent.
|
| 188 |
+
"""
|
| 189 |
+
if isinstance(path, list):
|
| 190 |
+
return [cls._strip_protocol(p) for p in path]
|
| 191 |
+
path = stringify_path(path)
|
| 192 |
+
if path.startswith("ia://"):
|
| 193 |
+
path = path[5:]
|
| 194 |
+
elif "://" in path:
|
| 195 |
+
return path
|
| 196 |
+
return cls.download_url + path.lstrip("/")
|
| 197 |
+
|
| 198 |
+
def unstrip_protocol(self, name):
|
| 199 |
+
if name.startswith(self.download_url):
|
| 200 |
+
return "ia://" + name[len(self.download_url) :]
|
| 201 |
+
if name.startswith("ia://"):
|
| 202 |
+
return name
|
| 203 |
+
return "ia://" + name.lstrip("/")
|
| 204 |
+
|
| 205 |
+
# archive.org answers a restricted item with 403 (401 for a bad LOW key).
|
| 206 |
+
# HTTPFileSystem reports a failed HEAD+GET as FileNotFoundError and any other
|
| 207 |
+
# status through raise_for_status(); both become PermissionError so callers can
|
| 208 |
+
# tell "no such file" from "log in". The two methods callers reach with an
|
| 209 |
+
# ia:// path directly (open() strips before _open) map it here too.
|
| 210 |
+
async def _info(self, url, **kwargs):
|
| 211 |
+
url = self._strip_protocol(url)
|
| 212 |
+
try:
|
| 213 |
+
return await super()._info(url, **kwargs)
|
| 214 |
+
except FileNotFoundError as exc:
|
| 215 |
+
cause = exc.__cause__
|
| 216 |
+
if isinstance(cause, aiohttp.ClientResponseError) and cause.status in (
|
| 217 |
+
401,
|
| 218 |
+
403,
|
| 219 |
+
):
|
| 220 |
+
raise PermissionError(url) from cause
|
| 221 |
+
raise
|
| 222 |
+
|
| 223 |
+
async def _cat_file(self, url, start=None, end=None, **kwargs):
|
| 224 |
+
url = self._strip_protocol(url)
|
| 225 |
+
return await super()._cat_file(url, start=start, end=end, **kwargs)
|
| 226 |
+
|
| 227 |
+
def _raise_not_found_for_status(self, response, url):
|
| 228 |
+
if response.status in (401, 403):
|
| 229 |
+
raise PermissionError(url)
|
| 230 |
+
super()._raise_not_found_for_status(response, url)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/jupyter.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Ask for the raw file; by default notebooks come back as parsed JSON
|
| 65 |
+
r = self.session.get(
|
| 66 |
+
f"{self.url}/{path}", params={"type": "file", "format": "base64"}
|
| 67 |
+
)
|
| 68 |
+
if r.status_code == 404:
|
| 69 |
+
raise FileNotFoundError(path)
|
| 70 |
+
r.raise_for_status()
|
| 71 |
+
out = r.json()
|
| 72 |
+
if out["format"] == "text":
|
| 73 |
+
# data should be binary
|
| 74 |
+
b = out["content"].encode()
|
| 75 |
+
else:
|
| 76 |
+
b = base64.b64decode(out["content"])
|
| 77 |
+
return b[start:end]
|
| 78 |
+
|
| 79 |
+
def pipe_file(self, path, value, **_):
|
| 80 |
+
path = self._strip_protocol(path)
|
| 81 |
+
json = {
|
| 82 |
+
"name": path.rsplit("/", 1)[-1],
|
| 83 |
+
"path": path,
|
| 84 |
+
"size": len(value),
|
| 85 |
+
"content": base64.b64encode(value).decode(),
|
| 86 |
+
"format": "base64",
|
| 87 |
+
"type": "file",
|
| 88 |
+
}
|
| 89 |
+
self.session.put(f"{self.url}/{path}", json=json)
|
| 90 |
+
|
| 91 |
+
def mkdir(self, path, create_parents=True, **kwargs):
|
| 92 |
+
path = self._strip_protocol(path)
|
| 93 |
+
if create_parents and "/" in path:
|
| 94 |
+
self.mkdir(path.rsplit("/", 1)[0], True)
|
| 95 |
+
json = {
|
| 96 |
+
"name": path.rsplit("/", 1)[-1],
|
| 97 |
+
"path": path,
|
| 98 |
+
"size": None,
|
| 99 |
+
"content": None,
|
| 100 |
+
"type": "directory",
|
| 101 |
+
}
|
| 102 |
+
self.session.put(f"{self.url}/{path}", json=json)
|
| 103 |
+
|
| 104 |
+
def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
|
| 105 |
+
if path1 == path2:
|
| 106 |
+
return
|
| 107 |
+
self.session.patch(f"{self.url}/{path1}", json={"path": path2})
|
| 108 |
+
|
| 109 |
+
def _rm(self, path):
|
| 110 |
+
path = self._strip_protocol(path)
|
| 111 |
+
self.session.delete(f"{self.url}/{path}")
|
| 112 |
+
|
| 113 |
+
def _open(self, path, mode="rb", **kwargs):
|
| 114 |
+
path = self._strip_protocol(path)
|
| 115 |
+
if mode == "rb":
|
| 116 |
+
data = self.cat_file(path)
|
| 117 |
+
return io.BytesIO(data)
|
| 118 |
+
else:
|
| 119 |
+
return SimpleFileWriter(self, path, mode="wb")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class SimpleFileWriter(fsspec.spec.AbstractBufferedFile):
|
| 123 |
+
def _upload_chunk(self, final=False):
|
| 124 |
+
"""Never uploads a chunk until file is done
|
| 125 |
+
|
| 126 |
+
Not suitable for large files
|
| 127 |
+
"""
|
| 128 |
+
if final is False:
|
| 129 |
+
return False
|
| 130 |
+
self.buffer.seek(0)
|
| 131 |
+
data = self.buffer.read()
|
| 132 |
+
self.fs.pipe_file(self.path, data)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/libarchive.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 cls._normalize_path(super()._strip_protocol(path))
|
| 143 |
+
|
| 144 |
+
@staticmethod
|
| 145 |
+
def _normalize_path(path):
|
| 146 |
+
return "/".join(part for part in path.split("/") if part not in ("", "."))
|
| 147 |
+
|
| 148 |
+
def ls(self, path, detail=True, **kwargs):
|
| 149 |
+
entries = super().ls(path, detail=detail, **kwargs)
|
| 150 |
+
return [entry for entry in entries if (entry["name"] if detail else entry)]
|
| 151 |
+
|
| 152 |
+
def _get_dirs(self):
|
| 153 |
+
fields = {
|
| 154 |
+
"name": "pathname",
|
| 155 |
+
"size": "size",
|
| 156 |
+
"created": "ctime",
|
| 157 |
+
"mode": "mode",
|
| 158 |
+
"uid": "uid",
|
| 159 |
+
"gid": "gid",
|
| 160 |
+
"mtime": "mtime",
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
if self.dir_cache is not None:
|
| 164 |
+
return
|
| 165 |
+
|
| 166 |
+
self.dir_cache = {}
|
| 167 |
+
self._member_names = {}
|
| 168 |
+
list_names = []
|
| 169 |
+
with self._open_archive() as arc:
|
| 170 |
+
for entry in arc:
|
| 171 |
+
if not entry.isdir and not entry.isfile:
|
| 172 |
+
# Skip symbolic links, fifo entries, etc.
|
| 173 |
+
continue
|
| 174 |
+
f = {key: getattr(entry, fields[key]) for key in fields}
|
| 175 |
+
f["type"] = "directory" if entry.isdir else "file"
|
| 176 |
+
f["name"] = self._normalize_path(f["name"])
|
| 177 |
+
list_names.append(f["name"])
|
| 178 |
+
|
| 179 |
+
self.dir_cache[f["name"]] = f
|
| 180 |
+
self._member_names[f["name"]] = entry.pathname
|
| 181 |
+
# libarchive does not seem to return an entry for the directories (at least
|
| 182 |
+
# not in all formats), so get the directories names from the files names
|
| 183 |
+
for dirname in self._all_dirnames(list_names):
|
| 184 |
+
self.dir_cache.setdefault(
|
| 185 |
+
dirname, {"name": dirname, "size": 0, "type": "directory"}
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def _open(
|
| 189 |
+
self,
|
| 190 |
+
path,
|
| 191 |
+
mode="rb",
|
| 192 |
+
block_size=None,
|
| 193 |
+
autocommit=True,
|
| 194 |
+
cache_options=None,
|
| 195 |
+
**kwargs,
|
| 196 |
+
):
|
| 197 |
+
path = self._strip_protocol(path)
|
| 198 |
+
if mode != "rb":
|
| 199 |
+
raise NotImplementedError
|
| 200 |
+
if not self.isfile(path):
|
| 201 |
+
raise self._not_a_file(path)
|
| 202 |
+
|
| 203 |
+
data = b""
|
| 204 |
+
with self._open_archive() as arc:
|
| 205 |
+
for entry in arc:
|
| 206 |
+
if entry.pathname != self._member_names[path]:
|
| 207 |
+
continue
|
| 208 |
+
|
| 209 |
+
if entry.size == 0:
|
| 210 |
+
# empty file, so there are no blocks
|
| 211 |
+
data = b""
|
| 212 |
+
continue
|
| 213 |
+
|
| 214 |
+
for block in entry.get_blocks(entry.size):
|
| 215 |
+
data = block
|
| 216 |
+
break
|
| 217 |
+
else:
|
| 218 |
+
raise ValueError
|
| 219 |
+
return MemoryFile(fs=self, path=path, data=data)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/local.py
ADDED
|
@@ -0,0 +1,537 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
import io
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import os.path as osp
|
| 6 |
+
import shutil
|
| 7 |
+
import stat
|
| 8 |
+
import tempfile
|
| 9 |
+
from functools import lru_cache
|
| 10 |
+
|
| 11 |
+
from fsspec.compression import compr
|
| 12 |
+
from fsspec.core import get_compression
|
| 13 |
+
from fsspec.utils import isfilelike, stringify_path
|
| 14 |
+
|
| 15 |
+
from ..spec import AbstractFileSystem
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger("fsspec.local")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class LocalFileSystem(AbstractFileSystem):
|
| 21 |
+
"""Interface to files on local storage
|
| 22 |
+
|
| 23 |
+
Parameters
|
| 24 |
+
----------
|
| 25 |
+
auto_mkdir: bool
|
| 26 |
+
Whether, when opening a file, the directory containing it should
|
| 27 |
+
be created (if it doesn't already exist). This is assumed by pyarrow
|
| 28 |
+
code.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
root_marker = "/"
|
| 32 |
+
protocol = "file", "local"
|
| 33 |
+
local_file = True
|
| 34 |
+
|
| 35 |
+
def __init__(self, auto_mkdir=False, **kwargs):
|
| 36 |
+
super().__init__(**kwargs)
|
| 37 |
+
self.auto_mkdir = auto_mkdir
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def fsid(self):
|
| 41 |
+
return "local"
|
| 42 |
+
|
| 43 |
+
def mkdir(self, path, create_parents=True, **kwargs):
|
| 44 |
+
path = self._strip_protocol(path)
|
| 45 |
+
if self.exists(path):
|
| 46 |
+
raise FileExistsError(path)
|
| 47 |
+
if create_parents:
|
| 48 |
+
self.makedirs(path, exist_ok=True)
|
| 49 |
+
else:
|
| 50 |
+
os.mkdir(path, **kwargs)
|
| 51 |
+
|
| 52 |
+
def makedirs(self, path, exist_ok=False):
|
| 53 |
+
path = self._strip_protocol(path)
|
| 54 |
+
os.makedirs(path, exist_ok=exist_ok)
|
| 55 |
+
|
| 56 |
+
def rmdir(self, path):
|
| 57 |
+
path = self._strip_protocol(path)
|
| 58 |
+
os.rmdir(path)
|
| 59 |
+
|
| 60 |
+
def ls(self, path, detail=False, **kwargs):
|
| 61 |
+
path = self._strip_protocol(path)
|
| 62 |
+
path_info = self.info(path)
|
| 63 |
+
infos = []
|
| 64 |
+
if path_info["type"] == "directory":
|
| 65 |
+
with os.scandir(path) as it:
|
| 66 |
+
for f in it:
|
| 67 |
+
try:
|
| 68 |
+
# Only get the info if requested since it is a bit expensive (the stat call inside)
|
| 69 |
+
# The strip_protocol is also used in info() and calls make_path_posix to always return posix paths
|
| 70 |
+
info = self.info(f) if detail else self._strip_protocol(f.path)
|
| 71 |
+
infos.append(info)
|
| 72 |
+
except FileNotFoundError:
|
| 73 |
+
pass
|
| 74 |
+
else:
|
| 75 |
+
infos = [path_info] if detail else [path_info["name"]]
|
| 76 |
+
|
| 77 |
+
return infos
|
| 78 |
+
|
| 79 |
+
def info(self, path, **kwargs):
|
| 80 |
+
if isinstance(path, os.DirEntry):
|
| 81 |
+
# scandir DirEntry
|
| 82 |
+
out = path.stat(follow_symlinks=False)
|
| 83 |
+
link = path.is_symlink()
|
| 84 |
+
if path.is_dir(follow_symlinks=False):
|
| 85 |
+
t = "directory"
|
| 86 |
+
elif path.is_file(follow_symlinks=False):
|
| 87 |
+
t = "file"
|
| 88 |
+
else:
|
| 89 |
+
t = "other"
|
| 90 |
+
|
| 91 |
+
size = out.st_size
|
| 92 |
+
if link:
|
| 93 |
+
try:
|
| 94 |
+
out2 = path.stat(follow_symlinks=True)
|
| 95 |
+
size = out2.st_size
|
| 96 |
+
except OSError:
|
| 97 |
+
size = 0
|
| 98 |
+
path = self._strip_protocol(path.path)
|
| 99 |
+
else:
|
| 100 |
+
# str or path-like
|
| 101 |
+
path = self._strip_protocol(path)
|
| 102 |
+
out = os.stat(path, follow_symlinks=False)
|
| 103 |
+
link = stat.S_ISLNK(out.st_mode)
|
| 104 |
+
if link:
|
| 105 |
+
out = os.stat(path, follow_symlinks=True)
|
| 106 |
+
size = out.st_size
|
| 107 |
+
if stat.S_ISDIR(out.st_mode):
|
| 108 |
+
t = "directory"
|
| 109 |
+
elif stat.S_ISREG(out.st_mode):
|
| 110 |
+
t = "file"
|
| 111 |
+
else:
|
| 112 |
+
t = "other"
|
| 113 |
+
|
| 114 |
+
# Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime
|
| 115 |
+
created_time = getattr(out, "st_birthtime", out.st_ctime)
|
| 116 |
+
|
| 117 |
+
result = {
|
| 118 |
+
"name": path,
|
| 119 |
+
"size": size,
|
| 120 |
+
"type": t,
|
| 121 |
+
"created": created_time,
|
| 122 |
+
"islink": link,
|
| 123 |
+
}
|
| 124 |
+
for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]:
|
| 125 |
+
result[field] = getattr(out, f"st_{field}")
|
| 126 |
+
if link:
|
| 127 |
+
result["destination"] = os.readlink(path)
|
| 128 |
+
return result
|
| 129 |
+
|
| 130 |
+
def lexists(self, path, **kwargs):
|
| 131 |
+
return osp.lexists(self._strip_protocol(path))
|
| 132 |
+
|
| 133 |
+
def cp_file(self, path1, path2, **kwargs):
|
| 134 |
+
path1 = self._strip_protocol(path1)
|
| 135 |
+
path2 = self._strip_protocol(path2)
|
| 136 |
+
if self.auto_mkdir:
|
| 137 |
+
self.makedirs(self._parent(path2), exist_ok=True)
|
| 138 |
+
if self.isfile(path1):
|
| 139 |
+
shutil.copyfile(path1, path2)
|
| 140 |
+
elif self.isdir(path1):
|
| 141 |
+
self.mkdirs(path2, exist_ok=True)
|
| 142 |
+
else:
|
| 143 |
+
raise FileNotFoundError(path1)
|
| 144 |
+
|
| 145 |
+
def isfile(self, path):
|
| 146 |
+
path = self._strip_protocol(path)
|
| 147 |
+
return os.path.isfile(path)
|
| 148 |
+
|
| 149 |
+
def isdir(self, path):
|
| 150 |
+
path = self._strip_protocol(path)
|
| 151 |
+
return os.path.isdir(path)
|
| 152 |
+
|
| 153 |
+
def get_file(self, path1, path2, callback=None, **kwargs):
|
| 154 |
+
if isfilelike(path2):
|
| 155 |
+
with open(self._strip_protocol(path1), "rb") as f:
|
| 156 |
+
shutil.copyfileobj(f, path2)
|
| 157 |
+
else:
|
| 158 |
+
return self.cp_file(path1, path2, **kwargs)
|
| 159 |
+
|
| 160 |
+
def put_file(self, path1, path2, callback=None, mode="overwrite", **kwargs):
|
| 161 |
+
if mode == "create" and self.exists(path2):
|
| 162 |
+
raise FileExistsError(path2)
|
| 163 |
+
return self.cp_file(path1, path2, **kwargs)
|
| 164 |
+
|
| 165 |
+
def mv(self, path1, path2, recursive: bool = True, **kwargs):
|
| 166 |
+
"""Move files/directories
|
| 167 |
+
For the specific case of local, all ops on directories are recursive and
|
| 168 |
+
the recursive= kwarg is ignored.
|
| 169 |
+
"""
|
| 170 |
+
path1 = self._strip_protocol(path1)
|
| 171 |
+
path2 = self._strip_protocol(path2)
|
| 172 |
+
|
| 173 |
+
if self.auto_mkdir:
|
| 174 |
+
self.makedirs(self._parent(path2), exist_ok=True)
|
| 175 |
+
|
| 176 |
+
shutil.move(path1, path2)
|
| 177 |
+
|
| 178 |
+
def link(self, src, dst, **kwargs):
|
| 179 |
+
src = self._strip_protocol(src)
|
| 180 |
+
dst = self._strip_protocol(dst)
|
| 181 |
+
os.link(src, dst, **kwargs)
|
| 182 |
+
|
| 183 |
+
def symlink(self, src, dst, **kwargs):
|
| 184 |
+
src = self._strip_protocol(src)
|
| 185 |
+
dst = self._strip_protocol(dst)
|
| 186 |
+
os.symlink(src, dst, **kwargs)
|
| 187 |
+
|
| 188 |
+
def islink(self, path) -> bool:
|
| 189 |
+
return os.path.islink(self._strip_protocol(path))
|
| 190 |
+
|
| 191 |
+
def rm_file(self, path):
|
| 192 |
+
os.remove(self._strip_protocol(path))
|
| 193 |
+
|
| 194 |
+
def rm(self, path, recursive=False, maxdepth=None):
|
| 195 |
+
if not isinstance(path, list):
|
| 196 |
+
path = [path]
|
| 197 |
+
|
| 198 |
+
for p in path:
|
| 199 |
+
p = self._strip_protocol(p)
|
| 200 |
+
if self.isdir(p) and not self.islink(p):
|
| 201 |
+
if not recursive:
|
| 202 |
+
raise ValueError("Cannot delete directory, set recursive=True")
|
| 203 |
+
if osp.abspath(p) == os.getcwd():
|
| 204 |
+
raise ValueError("Cannot delete current working directory")
|
| 205 |
+
if maxdepth is None:
|
| 206 |
+
shutil.rmtree(p)
|
| 207 |
+
else:
|
| 208 |
+
# only delete down to maxdepth; a directory still holding
|
| 209 |
+
# deeper files is kept
|
| 210 |
+
paths = self.expand_path(p, recursive=True, maxdepth=maxdepth)
|
| 211 |
+
for sub in reversed(paths):
|
| 212 |
+
if not self.isdir(sub) or self.islink(sub):
|
| 213 |
+
os.remove(sub)
|
| 214 |
+
elif not os.listdir(sub):
|
| 215 |
+
os.rmdir(sub)
|
| 216 |
+
else:
|
| 217 |
+
os.remove(p)
|
| 218 |
+
|
| 219 |
+
def unstrip_protocol(self, name):
|
| 220 |
+
protocol = self.protocol if isinstance(self.protocol, str) else self.protocol[0]
|
| 221 |
+
name = self._strip_protocol(name) # normalise for local/win/...
|
| 222 |
+
return f"{protocol}://{name}"
|
| 223 |
+
|
| 224 |
+
def _open(self, path, mode="rb", block_size=None, **kwargs):
|
| 225 |
+
path = self._strip_protocol(path)
|
| 226 |
+
if self.auto_mkdir and ("w" in mode or "x" in mode or "a" in mode):
|
| 227 |
+
self.makedirs(self._parent(path), exist_ok=True)
|
| 228 |
+
return LocalFileOpener(path, mode, fs=self, **kwargs)
|
| 229 |
+
|
| 230 |
+
def touch(self, path, truncate=True, **kwargs):
|
| 231 |
+
path = self._strip_protocol(path)
|
| 232 |
+
if self.auto_mkdir:
|
| 233 |
+
self.makedirs(self._parent(path), exist_ok=True)
|
| 234 |
+
if self.exists(path):
|
| 235 |
+
os.utime(path, None)
|
| 236 |
+
else:
|
| 237 |
+
open(path, "a").close()
|
| 238 |
+
if truncate:
|
| 239 |
+
os.truncate(path, 0)
|
| 240 |
+
|
| 241 |
+
def created(self, path):
|
| 242 |
+
info = self.info(path=path)
|
| 243 |
+
return datetime.datetime.fromtimestamp(
|
| 244 |
+
info["created"], tz=datetime.timezone.utc
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
def modified(self, path):
|
| 248 |
+
info = self.info(path=path)
|
| 249 |
+
return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc)
|
| 250 |
+
|
| 251 |
+
@classmethod
|
| 252 |
+
def _parent(cls, path):
|
| 253 |
+
path = cls._strip_protocol(path)
|
| 254 |
+
if os.sep == "/":
|
| 255 |
+
# posix native
|
| 256 |
+
return path.rsplit("/", 1)[0] or "/"
|
| 257 |
+
else:
|
| 258 |
+
# NT
|
| 259 |
+
path_ = path.rsplit("/", 1)[0]
|
| 260 |
+
if len(path_) <= 3:
|
| 261 |
+
if path_[1:2] == ":":
|
| 262 |
+
# nt root (something like c:/)
|
| 263 |
+
return path_[0] + ":/"
|
| 264 |
+
# More cases may be required here
|
| 265 |
+
return path_
|
| 266 |
+
|
| 267 |
+
@classmethod
|
| 268 |
+
def _strip_protocol(cls, path):
|
| 269 |
+
path = stringify_path(path)
|
| 270 |
+
protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol
|
| 271 |
+
prefixes = (protocol + sep for protocol in protos for sep in ("://", ":"))
|
| 272 |
+
for prefix in prefixes:
|
| 273 |
+
if path.startswith(prefix):
|
| 274 |
+
path = path.removeprefix(prefix)
|
| 275 |
+
break
|
| 276 |
+
|
| 277 |
+
path = make_path_posix(path)
|
| 278 |
+
if os.sep != "/":
|
| 279 |
+
# This code-path is a stripped down version of
|
| 280 |
+
# > drive, path = ntpath.splitdrive(path)
|
| 281 |
+
if path[1:2] == ":":
|
| 282 |
+
# Absolute drive-letter path, e.g. X:\Windows
|
| 283 |
+
# Relative path with drive, e.g. X:Windows
|
| 284 |
+
drive, path = path[:2], path[2:]
|
| 285 |
+
elif path[:2] == "//":
|
| 286 |
+
# UNC drives, e.g. \\server\share or \\?\UNC\server\share
|
| 287 |
+
# Device drives, e.g. \\.\device or \\?\device
|
| 288 |
+
if (index1 := path.find("/", 2)) == -1 or (
|
| 289 |
+
index2 := path.find("/", index1 + 1)
|
| 290 |
+
) == -1:
|
| 291 |
+
drive, path = path, ""
|
| 292 |
+
else:
|
| 293 |
+
drive, path = path[:index2], path[index2:]
|
| 294 |
+
else:
|
| 295 |
+
# Relative path, e.g. Windows
|
| 296 |
+
drive = ""
|
| 297 |
+
|
| 298 |
+
path = path.rstrip("/") or cls.root_marker
|
| 299 |
+
return drive + path
|
| 300 |
+
|
| 301 |
+
else:
|
| 302 |
+
return path.rstrip("/") or cls.root_marker
|
| 303 |
+
|
| 304 |
+
def _isfilestore(self):
|
| 305 |
+
# Inheriting from DaskFileSystem makes this False (S3, etc. were)
|
| 306 |
+
# the original motivation. But we are a posix-like file system.
|
| 307 |
+
# See https://github.com/dask/dask/issues/5526
|
| 308 |
+
return True
|
| 309 |
+
|
| 310 |
+
def chmod(self, path, mode):
|
| 311 |
+
path = self._strip_protocol(path)
|
| 312 |
+
return os.chmod(path, mode)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def make_path_posix(path):
|
| 316 |
+
"""Make path generic and absolute for current OS"""
|
| 317 |
+
if not isinstance(path, str):
|
| 318 |
+
if isinstance(path, (list, set, tuple)):
|
| 319 |
+
return type(path)(make_path_posix(p) for p in path)
|
| 320 |
+
else:
|
| 321 |
+
path = stringify_path(path)
|
| 322 |
+
if not isinstance(path, str):
|
| 323 |
+
raise TypeError(f"could not convert {path!r} to string")
|
| 324 |
+
if os.sep == "/":
|
| 325 |
+
# Native posix
|
| 326 |
+
if path.startswith("/"):
|
| 327 |
+
# most common fast case for posix
|
| 328 |
+
return path
|
| 329 |
+
elif path.startswith("~"):
|
| 330 |
+
return osp.expanduser(path)
|
| 331 |
+
elif path.startswith("./"):
|
| 332 |
+
path = path[2:]
|
| 333 |
+
elif path == ".":
|
| 334 |
+
path = ""
|
| 335 |
+
return f"{os.getcwd()}/{path}"
|
| 336 |
+
else:
|
| 337 |
+
# NT handling
|
| 338 |
+
if path[0:1] == "/" and path[2:3] == ":":
|
| 339 |
+
# path is like "/c:/local/path"
|
| 340 |
+
path = path[1:]
|
| 341 |
+
if path[1:2] == ":":
|
| 342 |
+
# windows full path like "C:\\local\\path"
|
| 343 |
+
if len(path) == 2 or (len(path) == 3 and path[2] in "/\\"):
|
| 344 |
+
# nt root (something like c:/). A three-character "c:x" is not a
|
| 345 |
+
# root: it names "x" relative to that drive, so it falls through
|
| 346 |
+
# instead of being collapsed to the drive root.
|
| 347 |
+
return path[0] + ":/"
|
| 348 |
+
path = path.replace("\\", "/")
|
| 349 |
+
return path
|
| 350 |
+
elif path[0:1] == "~":
|
| 351 |
+
return make_path_posix(osp.expanduser(path))
|
| 352 |
+
elif path.startswith(("\\\\", "//")):
|
| 353 |
+
# windows UNC/DFS-style paths
|
| 354 |
+
return "//" + path[2:].replace("\\", "/")
|
| 355 |
+
elif path.startswith(("\\", "/")):
|
| 356 |
+
# windows relative path with root
|
| 357 |
+
path = path.replace("\\", "/")
|
| 358 |
+
return f"{osp.splitdrive(os.getcwd())[0]}{path}"
|
| 359 |
+
else:
|
| 360 |
+
path = path.replace("\\", "/")
|
| 361 |
+
if path.startswith("./"):
|
| 362 |
+
path = path[2:]
|
| 363 |
+
elif path == ".":
|
| 364 |
+
path = ""
|
| 365 |
+
return f"{make_path_posix(os.getcwd())}/{path}"
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def trailing_sep(path):
|
| 369 |
+
"""Return True if the path ends with a path separator.
|
| 370 |
+
|
| 371 |
+
A forward slash is always considered a path separator, even on Operating
|
| 372 |
+
Systems that normally use a backslash.
|
| 373 |
+
"""
|
| 374 |
+
# TODO: if all incoming paths were posix-compliant then separator would
|
| 375 |
+
# always be a forward slash, simplifying this function.
|
| 376 |
+
# See https://github.com/fsspec/filesystem_spec/pull/1250
|
| 377 |
+
return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep))
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
@lru_cache(maxsize=1)
|
| 381 |
+
def get_umask(mask: int = 0o666) -> int:
|
| 382 |
+
"""Get the current umask.
|
| 383 |
+
|
| 384 |
+
Follows https://stackoverflow.com/a/44130549 to get the umask.
|
| 385 |
+
Temporarily sets the umask to the given value, and then resets it to the
|
| 386 |
+
original value.
|
| 387 |
+
"""
|
| 388 |
+
value = os.umask(mask)
|
| 389 |
+
os.umask(value)
|
| 390 |
+
return value
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class LocalFileOpener(io.IOBase):
|
| 394 |
+
def __init__(
|
| 395 |
+
self, path, mode, autocommit=True, fs=None, compression=None, **kwargs
|
| 396 |
+
):
|
| 397 |
+
logger.debug("open file: %s", path)
|
| 398 |
+
self.path = path
|
| 399 |
+
self.mode = mode
|
| 400 |
+
self.fs = fs
|
| 401 |
+
self.f = None
|
| 402 |
+
self.autocommit = autocommit
|
| 403 |
+
self.compression = get_compression(path, compression)
|
| 404 |
+
self.blocksize = io.DEFAULT_BUFFER_SIZE
|
| 405 |
+
self._open()
|
| 406 |
+
|
| 407 |
+
def _open(self):
|
| 408 |
+
if self.f is None or self.f.closed:
|
| 409 |
+
if self.autocommit or "w" not in self.mode:
|
| 410 |
+
self.f = open(self.path, mode=self.mode)
|
| 411 |
+
if self.compression:
|
| 412 |
+
compress = compr[self.compression]
|
| 413 |
+
self.f = compress(self.f, mode=self.mode)
|
| 414 |
+
else:
|
| 415 |
+
# TODO: check if path is writable?
|
| 416 |
+
i, name = tempfile.mkstemp()
|
| 417 |
+
os.close(i) # we want normal open and normal buffered file
|
| 418 |
+
self.temp = name
|
| 419 |
+
self.f = open(name, mode=self.mode)
|
| 420 |
+
if "r" in self.mode:
|
| 421 |
+
self.size = self.f.seek(0, 2)
|
| 422 |
+
self.f.seek(0)
|
| 423 |
+
self.f.size = self.size
|
| 424 |
+
|
| 425 |
+
def _fetch_range(self, start, end):
|
| 426 |
+
# probably only used by cached FS
|
| 427 |
+
if "r" not in self.mode:
|
| 428 |
+
raise ValueError
|
| 429 |
+
self._open()
|
| 430 |
+
self.f.seek(start)
|
| 431 |
+
return self.f.read(end - start)
|
| 432 |
+
|
| 433 |
+
def __setstate__(self, state):
|
| 434 |
+
self.f = None
|
| 435 |
+
loc = state.pop("loc", None)
|
| 436 |
+
self.__dict__.update(state)
|
| 437 |
+
if "r" in state["mode"]:
|
| 438 |
+
self.f = None
|
| 439 |
+
self._open()
|
| 440 |
+
self.f.seek(loc)
|
| 441 |
+
|
| 442 |
+
def __getstate__(self):
|
| 443 |
+
d = self.__dict__.copy()
|
| 444 |
+
d.pop("f")
|
| 445 |
+
if "r" in self.mode:
|
| 446 |
+
d["loc"] = self.f.tell()
|
| 447 |
+
else:
|
| 448 |
+
if not self.f.closed:
|
| 449 |
+
raise ValueError("Cannot serialise open write-mode local file")
|
| 450 |
+
return d
|
| 451 |
+
|
| 452 |
+
def commit(self):
|
| 453 |
+
if self.autocommit:
|
| 454 |
+
raise RuntimeError("Can only commit if not already set to autocommit")
|
| 455 |
+
if not self.f.closed:
|
| 456 |
+
# a compression wrapper (e.g., GzipFile) does not close the file
|
| 457 |
+
# object it was given, so buffered bytes and any trailer may still
|
| 458 |
+
# be pending here. Windows also refuses to rename an open file.
|
| 459 |
+
self.f.close()
|
| 460 |
+
try:
|
| 461 |
+
shutil.move(self.temp, self.path)
|
| 462 |
+
except PermissionError as e:
|
| 463 |
+
# shutil.move raises PermissionError if os.rename
|
| 464 |
+
# and the default copy2 fallback with shutil.copystats fail.
|
| 465 |
+
# The file should be there nonetheless, but without copied permissions.
|
| 466 |
+
# If it doesn't exist, there was no permission to create the file.
|
| 467 |
+
if not os.path.exists(self.path):
|
| 468 |
+
raise e
|
| 469 |
+
else:
|
| 470 |
+
# If PermissionError is not raised, permissions can be set.
|
| 471 |
+
try:
|
| 472 |
+
mask = 0o666
|
| 473 |
+
os.chmod(self.path, mask & ~get_umask(mask))
|
| 474 |
+
except RuntimeError:
|
| 475 |
+
pass
|
| 476 |
+
|
| 477 |
+
def discard(self):
|
| 478 |
+
if self.autocommit:
|
| 479 |
+
raise RuntimeError("Cannot discard if set to autocommit")
|
| 480 |
+
os.remove(self.temp)
|
| 481 |
+
|
| 482 |
+
def readable(self) -> bool:
|
| 483 |
+
return True
|
| 484 |
+
|
| 485 |
+
def writable(self) -> bool:
|
| 486 |
+
return "r" not in self.mode
|
| 487 |
+
|
| 488 |
+
def read(self, *args, **kwargs):
|
| 489 |
+
return self.f.read(*args, **kwargs)
|
| 490 |
+
|
| 491 |
+
def write(self, *args, **kwargs):
|
| 492 |
+
return self.f.write(*args, **kwargs)
|
| 493 |
+
|
| 494 |
+
def tell(self, *args, **kwargs):
|
| 495 |
+
return self.f.tell(*args, **kwargs)
|
| 496 |
+
|
| 497 |
+
def seek(self, *args, **kwargs):
|
| 498 |
+
return self.f.seek(*args, **kwargs)
|
| 499 |
+
|
| 500 |
+
def seekable(self, *args, **kwargs):
|
| 501 |
+
return self.f.seekable(*args, **kwargs)
|
| 502 |
+
|
| 503 |
+
def readline(self, *args, **kwargs):
|
| 504 |
+
return self.f.readline(*args, **kwargs)
|
| 505 |
+
|
| 506 |
+
def readlines(self, *args, **kwargs):
|
| 507 |
+
return self.f.readlines(*args, **kwargs)
|
| 508 |
+
|
| 509 |
+
def close(self):
|
| 510 |
+
return self.f.close()
|
| 511 |
+
|
| 512 |
+
def truncate(self, size=None) -> int:
|
| 513 |
+
return self.f.truncate(size)
|
| 514 |
+
|
| 515 |
+
@property
|
| 516 |
+
def closed(self):
|
| 517 |
+
return self.f.closed
|
| 518 |
+
|
| 519 |
+
def fileno(self):
|
| 520 |
+
return self.raw.fileno()
|
| 521 |
+
|
| 522 |
+
def flush(self) -> None:
|
| 523 |
+
self.f.flush()
|
| 524 |
+
|
| 525 |
+
def __iter__(self):
|
| 526 |
+
return self.f.__iter__()
|
| 527 |
+
|
| 528 |
+
def __getattr__(self, item):
|
| 529 |
+
return getattr(self.f, item)
|
| 530 |
+
|
| 531 |
+
def __enter__(self):
|
| 532 |
+
self._incontext = True
|
| 533 |
+
return self
|
| 534 |
+
|
| 535 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 536 |
+
self._incontext = False
|
| 537 |
+
self.f.__exit__(exc_type, exc_value, traceback)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/memory.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
from errno import ENOTEMPTY
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
from pathlib import PurePath, PureWindowsPath
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from fsspec import AbstractFileSystem
|
| 11 |
+
from fsspec.implementations.local import LocalFileSystem
|
| 12 |
+
from fsspec.utils import stringify_path, tokenize
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger("fsspec.memoryfs")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MemoryFileSystem(AbstractFileSystem):
|
| 18 |
+
"""A filesystem based on a dict of BytesIO objects
|
| 19 |
+
|
| 20 |
+
By default, instances share a global in-memory filesystem. Pass
|
| 21 |
+
``global_store=False, skip_instance_cache=True`` to create a new instance
|
| 22 |
+
with an independent store instead.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
store: dict[str, Any] = {} # shared by default
|
| 26 |
+
pseudo_dirs = [""] # shared by default
|
| 27 |
+
protocol = "memory"
|
| 28 |
+
root_marker = "/"
|
| 29 |
+
|
| 30 |
+
def __init__(self, *args, global_store=True, **kwargs):
|
| 31 |
+
"""Create a memory filesystem.
|
| 32 |
+
|
| 33 |
+
Parameters
|
| 34 |
+
----------
|
| 35 |
+
global_store: bool
|
| 36 |
+
Share files and directories with other default instances. If False,
|
| 37 |
+
each instance starts with an empty, independent store. The normal
|
| 38 |
+
instance cache still applies; pass ``skip_instance_cache=True``
|
| 39 |
+
to create a new instance on every call. Pickling an
|
| 40 |
+
independent filesystem copies its files and directories; pickling a
|
| 41 |
+
global filesystem retains the reference to the global store.
|
| 42 |
+
"""
|
| 43 |
+
super().__init__(*args, **kwargs)
|
| 44 |
+
self.global_store = global_store
|
| 45 |
+
if not global_store:
|
| 46 |
+
self.store = {}
|
| 47 |
+
self.pseudo_dirs = [""]
|
| 48 |
+
|
| 49 |
+
@property
|
| 50 |
+
def _fs_token(self):
|
| 51 |
+
if self.global_store:
|
| 52 |
+
return super()._fs_token
|
| 53 |
+
return tokenize(super()._fs_token, id(self))
|
| 54 |
+
|
| 55 |
+
def __reduce__(self):
|
| 56 |
+
reduced = super().__reduce__()
|
| 57 |
+
if self.global_store:
|
| 58 |
+
return reduced
|
| 59 |
+
factory, (cls, args, kwargs) = reduced
|
| 60 |
+
# Restore into a new instance even when the source is cached.
|
| 61 |
+
kwargs = {**kwargs, "skip_instance_cache": True}
|
| 62 |
+
# Pickle's memo preserves the cycle through each MemoryFile.fs.
|
| 63 |
+
return (
|
| 64 |
+
factory,
|
| 65 |
+
(cls, args, kwargs),
|
| 66 |
+
{"store": self.store, "pseudo_dirs": self.pseudo_dirs},
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
@classmethod
|
| 70 |
+
def _strip_protocol(cls, path):
|
| 71 |
+
if isinstance(path, PurePath):
|
| 72 |
+
if isinstance(path, PureWindowsPath):
|
| 73 |
+
return LocalFileSystem._strip_protocol(path)
|
| 74 |
+
else:
|
| 75 |
+
path = stringify_path(path)
|
| 76 |
+
|
| 77 |
+
path = path.removeprefix("memory://")
|
| 78 |
+
if "::" in path or "://" in path:
|
| 79 |
+
return path.rstrip("/")
|
| 80 |
+
path = path.lstrip("/").rstrip("/")
|
| 81 |
+
return "/" + path if path else ""
|
| 82 |
+
|
| 83 |
+
def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
|
| 84 |
+
# The base implementation calls ls() once per directory, and each ls()
|
| 85 |
+
# scans the whole store, giving O(n_dirs * n_entries) behaviour
|
| 86 |
+
# for a tree. Since the store is a flat mapping of every path, the same
|
| 87 |
+
# result can be produced with a single pass over it.
|
| 88 |
+
if maxdepth is not None and maxdepth < 1:
|
| 89 |
+
raise ValueError("maxdepth must be at least 1")
|
| 90 |
+
path = self._strip_protocol(path)
|
| 91 |
+
if path in self.store:
|
| 92 |
+
# path is itself a file
|
| 93 |
+
if not detail:
|
| 94 |
+
return [path]
|
| 95 |
+
filelike = self.store[path]
|
| 96 |
+
return {
|
| 97 |
+
path: {
|
| 98 |
+
"name": path,
|
| 99 |
+
"size": filelike.size,
|
| 100 |
+
"type": "file",
|
| 101 |
+
"created": filelike.created.timestamp(),
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
# Uniform prefix so that the search root "" (the filesystem root) and a
|
| 106 |
+
# nested path are handled the same way; rel depth is rel.count("/") + 1.
|
| 107 |
+
prefix = path + "/" if path else "/"
|
| 108 |
+
out = {}
|
| 109 |
+
dirs = {}
|
| 110 |
+
|
| 111 |
+
def add_ancestor_dirs(name):
|
| 112 |
+
# Register every directory implied between ``path`` and ``name`` that
|
| 113 |
+
# is within maxdepth, mirroring how walk() surfaces implied dirs.
|
| 114 |
+
idx = name.rfind("/")
|
| 115 |
+
while idx > len(path):
|
| 116 |
+
parent = name[:idx]
|
| 117 |
+
if parent in dirs:
|
| 118 |
+
break
|
| 119 |
+
rel = parent[len(prefix) :]
|
| 120 |
+
if maxdepth is None or rel.count("/") + 1 <= maxdepth:
|
| 121 |
+
dirs[parent] = {"name": parent, "size": 0, "type": "directory"}
|
| 122 |
+
idx = parent.rfind("/")
|
| 123 |
+
|
| 124 |
+
# `store` may be shared by multiple MemoryFileSystem instances, so iterate a
|
| 125 |
+
# snapshot: a concurrent create/delete would otherwise raise
|
| 126 |
+
# "dictionary changed size during iteration". ls() does the same.
|
| 127 |
+
for name, filelike in tuple(self.store.items()):
|
| 128 |
+
if not name.startswith(prefix):
|
| 129 |
+
continue
|
| 130 |
+
rel = name[len(prefix) :]
|
| 131 |
+
if withdirs:
|
| 132 |
+
add_ancestor_dirs(name)
|
| 133 |
+
if maxdepth is not None and rel.count("/") + 1 > maxdepth:
|
| 134 |
+
continue
|
| 135 |
+
out[name] = {
|
| 136 |
+
"name": name,
|
| 137 |
+
"size": filelike.size,
|
| 138 |
+
"type": "file",
|
| 139 |
+
"created": filelike.created.timestamp(),
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
if withdirs:
|
| 143 |
+
# Explicitly-created (possibly empty) directories live in pseudo_dirs.
|
| 144 |
+
for pdir in self.pseudo_dirs:
|
| 145 |
+
if pdir and pdir.startswith(prefix):
|
| 146 |
+
add_ancestor_dirs(pdir + "/")
|
| 147 |
+
out.update(dirs)
|
| 148 |
+
# Mirror the base find(): include the search root itself when it is
|
| 149 |
+
# a directory (needed for posix glob compliance).
|
| 150 |
+
if path != "" and self.isdir(path):
|
| 151 |
+
out[path] = self.info(path)
|
| 152 |
+
|
| 153 |
+
names = sorted(out)
|
| 154 |
+
return {name: out[name] for name in names} if detail else names
|
| 155 |
+
|
| 156 |
+
def ls(self, path, detail=True, **kwargs):
|
| 157 |
+
path = self._strip_protocol(path)
|
| 158 |
+
if path in self.store:
|
| 159 |
+
# there is a key with this exact name
|
| 160 |
+
if not detail:
|
| 161 |
+
return [path]
|
| 162 |
+
return [
|
| 163 |
+
{
|
| 164 |
+
"name": path,
|
| 165 |
+
"size": self.store[path].size,
|
| 166 |
+
"type": "file",
|
| 167 |
+
"created": self.store[path].created.timestamp(),
|
| 168 |
+
}
|
| 169 |
+
]
|
| 170 |
+
paths = set()
|
| 171 |
+
starter = path + "/"
|
| 172 |
+
out = []
|
| 173 |
+
for p2 in tuple(self.store):
|
| 174 |
+
if p2.startswith(starter):
|
| 175 |
+
if "/" not in p2[len(starter) :]:
|
| 176 |
+
# exact child
|
| 177 |
+
out.append(
|
| 178 |
+
{
|
| 179 |
+
"name": p2,
|
| 180 |
+
"size": self.store[p2].size,
|
| 181 |
+
"type": "file",
|
| 182 |
+
"created": self.store[p2].created.timestamp(),
|
| 183 |
+
}
|
| 184 |
+
)
|
| 185 |
+
elif len(p2) > len(starter):
|
| 186 |
+
# implied child directory
|
| 187 |
+
ppath = starter + p2[len(starter) :].split("/", 1)[0]
|
| 188 |
+
if ppath not in paths:
|
| 189 |
+
out = out or []
|
| 190 |
+
out.append(
|
| 191 |
+
{
|
| 192 |
+
"name": ppath,
|
| 193 |
+
"size": 0,
|
| 194 |
+
"type": "directory",
|
| 195 |
+
}
|
| 196 |
+
)
|
| 197 |
+
paths.add(ppath)
|
| 198 |
+
for p2 in self.pseudo_dirs:
|
| 199 |
+
if p2.startswith(starter):
|
| 200 |
+
if "/" not in p2[len(starter) :]:
|
| 201 |
+
# exact child pdir
|
| 202 |
+
if p2 not in paths:
|
| 203 |
+
out.append({"name": p2, "size": 0, "type": "directory"})
|
| 204 |
+
paths.add(p2)
|
| 205 |
+
else:
|
| 206 |
+
# directory implied by deeper pdir
|
| 207 |
+
ppath = starter + p2[len(starter) :].split("/", 1)[0]
|
| 208 |
+
if ppath not in paths:
|
| 209 |
+
out.append({"name": ppath, "size": 0, "type": "directory"})
|
| 210 |
+
paths.add(ppath)
|
| 211 |
+
if not out:
|
| 212 |
+
if path in self.pseudo_dirs:
|
| 213 |
+
# empty dir
|
| 214 |
+
return []
|
| 215 |
+
raise FileNotFoundError(path)
|
| 216 |
+
if detail:
|
| 217 |
+
return out
|
| 218 |
+
return sorted([f["name"] for f in out])
|
| 219 |
+
|
| 220 |
+
def mkdir(self, path, create_parents=True, **kwargs):
|
| 221 |
+
path = self._strip_protocol(path)
|
| 222 |
+
if path in self.store or path in self.pseudo_dirs:
|
| 223 |
+
raise FileExistsError(path)
|
| 224 |
+
if self._parent(path).strip("/") and self.isfile(self._parent(path)):
|
| 225 |
+
raise NotADirectoryError(self._parent(path))
|
| 226 |
+
if not create_parents and not self.isdir(self._parent(path)):
|
| 227 |
+
raise FileNotFoundError(self._parent(path))
|
| 228 |
+
if create_parents and self._parent(path).strip("/"):
|
| 229 |
+
try:
|
| 230 |
+
self.mkdir(self._parent(path), create_parents, **kwargs)
|
| 231 |
+
except FileExistsError:
|
| 232 |
+
pass
|
| 233 |
+
if path and path not in self.pseudo_dirs:
|
| 234 |
+
self.pseudo_dirs.append(path)
|
| 235 |
+
|
| 236 |
+
def makedirs(self, path, exist_ok=False):
|
| 237 |
+
try:
|
| 238 |
+
self.mkdir(path, create_parents=True)
|
| 239 |
+
except FileExistsError:
|
| 240 |
+
if not exist_ok or self.isfile(path):
|
| 241 |
+
raise
|
| 242 |
+
|
| 243 |
+
def pipe_file(self, path, value, mode="overwrite", **kwargs):
|
| 244 |
+
"""Set the bytes of given file
|
| 245 |
+
|
| 246 |
+
Avoids copies of the data if possible
|
| 247 |
+
"""
|
| 248 |
+
mode = "xb" if mode == "create" else "wb"
|
| 249 |
+
self.open(path, mode=mode, data=value)
|
| 250 |
+
|
| 251 |
+
def rmdir(self, path):
|
| 252 |
+
path = self._strip_protocol(path)
|
| 253 |
+
if path == "":
|
| 254 |
+
# silently avoid deleting FS root
|
| 255 |
+
return
|
| 256 |
+
if path in self.pseudo_dirs:
|
| 257 |
+
if not self.ls(path):
|
| 258 |
+
self.pseudo_dirs.remove(path)
|
| 259 |
+
else:
|
| 260 |
+
raise OSError(ENOTEMPTY, "Directory not empty", path)
|
| 261 |
+
else:
|
| 262 |
+
raise FileNotFoundError(path)
|
| 263 |
+
|
| 264 |
+
def info(self, path, **kwargs):
|
| 265 |
+
logger.debug("info: %s", path)
|
| 266 |
+
path = self._strip_protocol(path)
|
| 267 |
+
if path in self.pseudo_dirs or any(
|
| 268 |
+
p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs
|
| 269 |
+
):
|
| 270 |
+
return {
|
| 271 |
+
"name": path,
|
| 272 |
+
"size": 0,
|
| 273 |
+
"type": "directory",
|
| 274 |
+
}
|
| 275 |
+
elif path in self.store:
|
| 276 |
+
filelike = self.store[path]
|
| 277 |
+
return {
|
| 278 |
+
"name": path,
|
| 279 |
+
"size": filelike.size,
|
| 280 |
+
"type": "file",
|
| 281 |
+
"created": filelike.created.timestamp(),
|
| 282 |
+
}
|
| 283 |
+
else:
|
| 284 |
+
raise FileNotFoundError(path)
|
| 285 |
+
|
| 286 |
+
def _open(
|
| 287 |
+
self,
|
| 288 |
+
path,
|
| 289 |
+
mode="rb",
|
| 290 |
+
block_size=None,
|
| 291 |
+
autocommit=True,
|
| 292 |
+
cache_options=None,
|
| 293 |
+
**kwargs,
|
| 294 |
+
):
|
| 295 |
+
if mode in {"rb+", "wb+", "ab+", "xb+"}:
|
| 296 |
+
mode = mode[0] + "+b"
|
| 297 |
+
path = self._strip_protocol(path)
|
| 298 |
+
if "x" in mode and self.exists(path):
|
| 299 |
+
raise FileExistsError
|
| 300 |
+
if path in self.pseudo_dirs or (
|
| 301 |
+
path not in self.store and any(p.startswith(path + "/") for p in self.store)
|
| 302 |
+
):
|
| 303 |
+
raise IsADirectoryError(path)
|
| 304 |
+
parent = path
|
| 305 |
+
while len(parent) > 1:
|
| 306 |
+
parent = self._parent(parent)
|
| 307 |
+
if self.isfile(parent):
|
| 308 |
+
raise FileExistsError(parent)
|
| 309 |
+
if mode in ["rb", "ab", "r+b", "a+b"]:
|
| 310 |
+
if path in self.store:
|
| 311 |
+
f = self.store[path]
|
| 312 |
+
if self._intrans and "a" in mode:
|
| 313 |
+
# append to a copy so the store is unchanged until commit
|
| 314 |
+
f = MemoryFile(self, path, f.getvalue())
|
| 315 |
+
f.created = self.store[path].created
|
| 316 |
+
if "a" in mode:
|
| 317 |
+
# position at the end of file
|
| 318 |
+
f.seek(0, 2)
|
| 319 |
+
else:
|
| 320 |
+
# position at the beginning of file
|
| 321 |
+
f.seek(0)
|
| 322 |
+
return f
|
| 323 |
+
elif "a" in mode:
|
| 324 |
+
# append modes create the file if it does not exist, matching
|
| 325 |
+
# builtin open() and LocalFileSystem
|
| 326 |
+
m = MemoryFile(self, path, kwargs.get("data"))
|
| 327 |
+
if not self._intrans:
|
| 328 |
+
m.commit()
|
| 329 |
+
# position at the end of file, like the existing-file path above
|
| 330 |
+
m.seek(0, 2)
|
| 331 |
+
return m
|
| 332 |
+
else:
|
| 333 |
+
raise FileNotFoundError(path)
|
| 334 |
+
elif mode in {"wb", "w+b", "xb", "x+b"}:
|
| 335 |
+
if "x" in mode and self.exists(path):
|
| 336 |
+
raise FileExistsError
|
| 337 |
+
m = MemoryFile(self, path, kwargs.get("data"))
|
| 338 |
+
if not self._intrans:
|
| 339 |
+
m.commit()
|
| 340 |
+
return m
|
| 341 |
+
else:
|
| 342 |
+
name = self.__class__.__name__
|
| 343 |
+
raise ValueError(f"unsupported file mode for {name}: {mode!r}")
|
| 344 |
+
|
| 345 |
+
def cp_file(self, path1, path2, **kwargs):
|
| 346 |
+
path1 = self._strip_protocol(path1)
|
| 347 |
+
path2 = self._strip_protocol(path2)
|
| 348 |
+
source_is_file = self.isfile(path1)
|
| 349 |
+
if not source_is_file and not self.isdir(path1):
|
| 350 |
+
raise FileNotFoundError(path1)
|
| 351 |
+
parent = path2
|
| 352 |
+
while len(parent) > 1:
|
| 353 |
+
parent = self._parent(parent)
|
| 354 |
+
if self.isfile(parent):
|
| 355 |
+
raise FileExistsError(parent)
|
| 356 |
+
if source_is_file:
|
| 357 |
+
if self.isdir(path2):
|
| 358 |
+
raise IsADirectoryError(path2)
|
| 359 |
+
self.store[path2] = MemoryFile(
|
| 360 |
+
self, path2, self.store[path1].getvalue()
|
| 361 |
+
) # implicit copy
|
| 362 |
+
else:
|
| 363 |
+
if self.isfile(path2):
|
| 364 |
+
raise FileExistsError(path2)
|
| 365 |
+
if path2 not in self.pseudo_dirs:
|
| 366 |
+
self.pseudo_dirs.append(path2)
|
| 367 |
+
|
| 368 |
+
def cat_file(self, path, start=None, end=None, **kwargs):
|
| 369 |
+
logger.debug("cat: %s", path)
|
| 370 |
+
path = self._strip_protocol(path)
|
| 371 |
+
try:
|
| 372 |
+
return bytes(self.store[path].getbuffer()[start:end])
|
| 373 |
+
except KeyError as e:
|
| 374 |
+
raise FileNotFoundError(path) from e
|
| 375 |
+
|
| 376 |
+
def _rm(self, path):
|
| 377 |
+
path = self._strip_protocol(path)
|
| 378 |
+
try:
|
| 379 |
+
del self.store[path]
|
| 380 |
+
except KeyError as e:
|
| 381 |
+
raise FileNotFoundError(path) from e
|
| 382 |
+
|
| 383 |
+
def modified(self, path):
|
| 384 |
+
path = self._strip_protocol(path)
|
| 385 |
+
try:
|
| 386 |
+
return self.store[path].modified
|
| 387 |
+
except KeyError as e:
|
| 388 |
+
raise FileNotFoundError(path) from e
|
| 389 |
+
|
| 390 |
+
def created(self, path):
|
| 391 |
+
path = self._strip_protocol(path)
|
| 392 |
+
try:
|
| 393 |
+
return self.store[path].created
|
| 394 |
+
except KeyError as e:
|
| 395 |
+
raise FileNotFoundError(path) from e
|
| 396 |
+
|
| 397 |
+
def isfile(self, path):
|
| 398 |
+
path = self._strip_protocol(path)
|
| 399 |
+
return path in self.store
|
| 400 |
+
|
| 401 |
+
def rm(self, path, recursive=False, maxdepth=None):
|
| 402 |
+
if isinstance(path, str):
|
| 403 |
+
path = self._strip_protocol(path)
|
| 404 |
+
else:
|
| 405 |
+
path = [self._strip_protocol(p) for p in path]
|
| 406 |
+
paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
|
| 407 |
+
# A non-recursive expand keeps a literal path whether or not it exists,
|
| 408 |
+
# so record what exists before anything is deleted.
|
| 409 |
+
existed = {p for p in paths if self.exists(p)}
|
| 410 |
+
for p in reversed(paths):
|
| 411 |
+
if self.isfile(p):
|
| 412 |
+
self.rm_file(p)
|
| 413 |
+
elif not self.exists(p):
|
| 414 |
+
# A directory that is not in self.pseudo_dirs only exists while it
|
| 415 |
+
# has files under it, so deleting those files earlier in this loop
|
| 416 |
+
# makes it vanish. That is expected; a path that never existed is
|
| 417 |
+
# not, and raises like rm_file and the other filesystems do.
|
| 418 |
+
if p not in existed:
|
| 419 |
+
raise FileNotFoundError(p)
|
| 420 |
+
continue
|
| 421 |
+
elif maxdepth is not None and self.ls(p, detail=False):
|
| 422 |
+
# a directory still holding files deeper than maxdepth is kept
|
| 423 |
+
continue
|
| 424 |
+
else:
|
| 425 |
+
self.rmdir(p)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class MemoryFile(BytesIO):
|
| 429 |
+
"""A BytesIO which can't close and works as a context manager
|
| 430 |
+
|
| 431 |
+
Can initialise with data. Each path should only be active once at any moment.
|
| 432 |
+
|
| 433 |
+
No need to provide fs, path if auto-committing (default)
|
| 434 |
+
"""
|
| 435 |
+
|
| 436 |
+
def __init__(self, fs=None, path=None, data=None):
|
| 437 |
+
logger.debug("open file %s", path)
|
| 438 |
+
self.fs = fs
|
| 439 |
+
self.path = path
|
| 440 |
+
self.created = datetime.now(tz=timezone.utc)
|
| 441 |
+
self.modified = datetime.now(tz=timezone.utc)
|
| 442 |
+
if data:
|
| 443 |
+
super().__init__(data)
|
| 444 |
+
self.seek(0)
|
| 445 |
+
|
| 446 |
+
@property
|
| 447 |
+
def size(self):
|
| 448 |
+
return self.getbuffer().nbytes
|
| 449 |
+
|
| 450 |
+
def write(self, data):
|
| 451 |
+
written = super().write(data)
|
| 452 |
+
if written:
|
| 453 |
+
self.modified = datetime.now(tz=timezone.utc)
|
| 454 |
+
return written
|
| 455 |
+
|
| 456 |
+
def writelines(self, lines):
|
| 457 |
+
for line in lines:
|
| 458 |
+
self.write(line)
|
| 459 |
+
|
| 460 |
+
def truncate(self, size=None):
|
| 461 |
+
size = super().truncate(size)
|
| 462 |
+
self.modified = datetime.now(tz=timezone.utc)
|
| 463 |
+
return size
|
| 464 |
+
|
| 465 |
+
def __enter__(self):
|
| 466 |
+
return self
|
| 467 |
+
|
| 468 |
+
def close(self):
|
| 469 |
+
pass
|
| 470 |
+
|
| 471 |
+
def discard(self):
|
| 472 |
+
pass
|
| 473 |
+
|
| 474 |
+
def commit(self):
|
| 475 |
+
self.fs.store[self.path] = self
|
| 476 |
+
self.modified = datetime.now(tz=timezone.utc)
|
tasks/tasksmith-3bb3c78392c6/tests/source/fsspec/implementations/reference.py
ADDED
|
@@ -0,0 +1,1387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import collections
|
| 3 |
+
import io
|
| 4 |
+
import itertools
|
| 5 |
+
import logging
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
from functools import lru_cache
|
| 9 |
+
from itertools import chain
|
| 10 |
+
from typing import TYPE_CHECKING, Literal
|
| 11 |
+
|
| 12 |
+
import fsspec.core
|
| 13 |
+
from fsspec.spec import AbstractBufferedFile
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import ujson as json
|
| 17 |
+
except ImportError:
|
| 18 |
+
if not TYPE_CHECKING:
|
| 19 |
+
import json
|
| 20 |
+
|
| 21 |
+
from fsspec.asyn import AsyncFileSystem
|
| 22 |
+
from fsspec.callbacks import DEFAULT_CALLBACK
|
| 23 |
+
from fsspec.core import filesystem, open, split_protocol
|
| 24 |
+
from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
|
| 25 |
+
from fsspec.utils import (
|
| 26 |
+
check_contained,
|
| 27 |
+
isfilelike,
|
| 28 |
+
merge_offset_ranges,
|
| 29 |
+
other_paths,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
logger = logging.getLogger("fsspec.reference")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ReferenceNotReachable(RuntimeError):
|
| 36 |
+
def __init__(self, reference, target, *args):
|
| 37 |
+
super().__init__(*args)
|
| 38 |
+
self.reference = reference
|
| 39 |
+
self.target = target
|
| 40 |
+
|
| 41 |
+
def __str__(self):
|
| 42 |
+
return f'Reference "{self.reference}" failed to fetch target {self.target}'
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _first(d):
|
| 46 |
+
return next(iter(d.values()))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _inline_data(part):
|
| 50 |
+
"""The bytes an inline (in-memory) reference delivers to a reader.
|
| 51 |
+
|
| 52 |
+
A ``base64:`` prefix marks base64-encoded content; other text is encoded
|
| 53 |
+
as UTF-8. ``info`` and ``ls`` measure the result of this rather than the
|
| 54 |
+
stored form, so that a size always matches what ``cat`` returns.
|
| 55 |
+
"""
|
| 56 |
+
if isinstance(part, (str, bytes)):
|
| 57 |
+
return _decode_inline(part)
|
| 58 |
+
if hasattr(part, "to_bytes"):
|
| 59 |
+
part = part.to_bytes()
|
| 60 |
+
return _decode_inline(part)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@lru_cache(maxsize=1024)
|
| 64 |
+
def _decode_inline(part):
|
| 65 |
+
"""Decode a stored inline part once and stash the result.
|
| 66 |
+
|
| 67 |
+
The same inline value is decoded for ``cat`` and again for the length
|
| 68 |
+
check in ``info``/``ls``; caching avoids repeating the work for every
|
| 69 |
+
listing. Inline references are small and few, so a bounded cache is
|
| 70 |
+
enough.
|
| 71 |
+
"""
|
| 72 |
+
if isinstance(part, str):
|
| 73 |
+
part = part.encode()
|
| 74 |
+
if part.startswith(b"base64:"):
|
| 75 |
+
return base64.b64decode(part[7:])
|
| 76 |
+
return part
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _prot_in_references(path, references):
|
| 80 |
+
ref = references.get(path)
|
| 81 |
+
if isinstance(ref, (list, tuple)) and isinstance(ref[0], str):
|
| 82 |
+
return split_protocol(ref[0])[0] if ref[0] else ref[0]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _protocol_groups(paths, references):
|
| 86 |
+
if isinstance(paths, str):
|
| 87 |
+
return {_prot_in_references(paths, references): [paths]}
|
| 88 |
+
out = {}
|
| 89 |
+
for path in paths:
|
| 90 |
+
protocol = _prot_in_references(path, references)
|
| 91 |
+
out.setdefault(protocol, []).append(path)
|
| 92 |
+
return out
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class RefsValuesView(collections.abc.ValuesView):
|
| 96 |
+
def __iter__(self):
|
| 97 |
+
for val in self._mapping.zmetadata.values():
|
| 98 |
+
yield json.dumps(val).encode()
|
| 99 |
+
yield from self._mapping._items.values()
|
| 100 |
+
for field in self._mapping.listdir():
|
| 101 |
+
chunk_sizes = self._mapping._get_chunk_sizes(field)
|
| 102 |
+
if len(chunk_sizes) == 0:
|
| 103 |
+
yield self._mapping[field + "/0"]
|
| 104 |
+
continue
|
| 105 |
+
yield from self._mapping._generate_all_records(field)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class RefsItemsView(collections.abc.ItemsView):
|
| 109 |
+
def __iter__(self):
|
| 110 |
+
return zip(self._mapping.keys(), self._mapping.values())
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def ravel_multi_index(idx, sizes):
|
| 114 |
+
val = 0
|
| 115 |
+
mult = 1
|
| 116 |
+
for i, s in zip(idx[::-1], sizes[::-1]):
|
| 117 |
+
val += i * mult
|
| 118 |
+
mult *= s
|
| 119 |
+
return val
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class LazyReferenceMapper(collections.abc.MutableMapping):
|
| 123 |
+
"""This interface can be used to read/write references from Parquet stores.
|
| 124 |
+
It is not intended for other types of references.
|
| 125 |
+
It can be used with Kerchunk's MultiZarrToZarr method to combine
|
| 126 |
+
references into a parquet store.
|
| 127 |
+
Examples of this use-case can be found here:
|
| 128 |
+
https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage"""
|
| 129 |
+
|
| 130 |
+
# import is class level to prevent numpy dep requirement for fsspec
|
| 131 |
+
@property
|
| 132 |
+
def np(self):
|
| 133 |
+
import numpy as np
|
| 134 |
+
|
| 135 |
+
return np
|
| 136 |
+
|
| 137 |
+
@property
|
| 138 |
+
def pd(self):
|
| 139 |
+
import pandas as pd
|
| 140 |
+
|
| 141 |
+
return pd
|
| 142 |
+
|
| 143 |
+
def __init__(
|
| 144 |
+
self,
|
| 145 |
+
root,
|
| 146 |
+
fs=None,
|
| 147 |
+
out_root=None,
|
| 148 |
+
cache_size=128,
|
| 149 |
+
categorical_threshold=10,
|
| 150 |
+
engine: Literal["fastparquet", "pyarrow"] = "fastparquet",
|
| 151 |
+
):
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
This instance will be writable, storing changes in memory until full partitions
|
| 155 |
+
are accumulated or .flush() is called.
|
| 156 |
+
|
| 157 |
+
To create an empty lazy store, use .create()
|
| 158 |
+
|
| 159 |
+
Parameters
|
| 160 |
+
----------
|
| 161 |
+
root : str
|
| 162 |
+
Root of parquet store
|
| 163 |
+
fs : fsspec.AbstractFileSystem
|
| 164 |
+
fsspec filesystem object, default is local filesystem.
|
| 165 |
+
cache_size : int, default=128
|
| 166 |
+
Maximum size of LRU cache, where cache_size*record_size denotes
|
| 167 |
+
the total number of references that can be loaded in memory at once.
|
| 168 |
+
categorical_threshold : int
|
| 169 |
+
Encode urls as pandas.Categorical to reduce memory footprint if the ratio
|
| 170 |
+
of the number of unique urls to total number of refs for each variable
|
| 171 |
+
is greater than or equal to this number. (default 10)
|
| 172 |
+
engine: Literal["fastparquet","pyarrow"]
|
| 173 |
+
Engine choice for reading parquet files. (default is "fastparquet")
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
self.root = root
|
| 177 |
+
self.chunk_sizes = {}
|
| 178 |
+
self.cat_thresh = categorical_threshold
|
| 179 |
+
self.engine = engine
|
| 180 |
+
self.cache_size = cache_size
|
| 181 |
+
self.url = self.root + "/{field}/refs.{record}.parq"
|
| 182 |
+
# TODO: derive fs from `root`
|
| 183 |
+
self.fs = fsspec.filesystem("file") if fs is None else fs
|
| 184 |
+
self.out_root = self.fs.unstrip_protocol(out_root or self.root)
|
| 185 |
+
|
| 186 |
+
from importlib.util import find_spec
|
| 187 |
+
|
| 188 |
+
if self.engine == "pyarrow" and find_spec("pyarrow") is None:
|
| 189 |
+
raise ImportError("engine choice `pyarrow` is not installed.")
|
| 190 |
+
|
| 191 |
+
# Apply `lru_cache` decorator manually per instance.
|
| 192 |
+
# This way `self` reference is not held on class level.
|
| 193 |
+
# WARNING: However, this means that self and its members are not reflected
|
| 194 |
+
# in the cache key, so we expect they won't be mutated once a value is cached.
|
| 195 |
+
self.listdir = lru_cache()(self.listdir)
|
| 196 |
+
self._key_to_record = lru_cache(maxsize=4096)(self._key_to_record)
|
| 197 |
+
|
| 198 |
+
def __getattr__(self, item):
|
| 199 |
+
if item in ("_items", "record_size", "zmetadata"):
|
| 200 |
+
self.setup()
|
| 201 |
+
# avoid possible recursion if setup fails somehow
|
| 202 |
+
return self.__dict__[item]
|
| 203 |
+
raise AttributeError(item)
|
| 204 |
+
|
| 205 |
+
def setup(self):
|
| 206 |
+
self._items = {}
|
| 207 |
+
self._items[".zmetadata"] = self.fs.cat_file(
|
| 208 |
+
"/".join([self.root, ".zmetadata"])
|
| 209 |
+
)
|
| 210 |
+
met = json.loads(self._items[".zmetadata"])
|
| 211 |
+
self.record_size = met["record_size"]
|
| 212 |
+
self.zmetadata = met["metadata"]
|
| 213 |
+
|
| 214 |
+
# Define function to open and decompress refs
|
| 215 |
+
@lru_cache(maxsize=self.cache_size)
|
| 216 |
+
def open_refs(field, record):
|
| 217 |
+
"""cached parquet file loader"""
|
| 218 |
+
path = self.url.format(field=field, record=record)
|
| 219 |
+
data = io.BytesIO(self.fs.cat_file(path))
|
| 220 |
+
try:
|
| 221 |
+
df = self.pd.read_parquet(data, engine=self.engine)
|
| 222 |
+
refs = {c: df[c].to_numpy(copy=True) for c in df.columns}
|
| 223 |
+
except OSError:
|
| 224 |
+
refs = None
|
| 225 |
+
return refs
|
| 226 |
+
|
| 227 |
+
self.open_refs = open_refs
|
| 228 |
+
|
| 229 |
+
@staticmethod
|
| 230 |
+
def create(root, storage_options=None, fs=None, record_size=10000, **kwargs):
|
| 231 |
+
"""Make empty parquet reference set
|
| 232 |
+
|
| 233 |
+
First deletes the contents of the given directory, if it exists.
|
| 234 |
+
|
| 235 |
+
Parameters
|
| 236 |
+
----------
|
| 237 |
+
root: str
|
| 238 |
+
Directory to contain the output; will be created
|
| 239 |
+
storage_options: dict | None
|
| 240 |
+
For making the filesystem to use for writing is fs is None
|
| 241 |
+
fs: FileSystem | None
|
| 242 |
+
Filesystem for writing
|
| 243 |
+
record_size: int
|
| 244 |
+
Number of references per parquet file
|
| 245 |
+
kwargs: passed to __init__
|
| 246 |
+
|
| 247 |
+
Returns
|
| 248 |
+
-------
|
| 249 |
+
LazyReferenceMapper instance
|
| 250 |
+
"""
|
| 251 |
+
met = {"metadata": {}, "record_size": record_size}
|
| 252 |
+
if fs is None:
|
| 253 |
+
fs, root = fsspec.core.url_to_fs(root, **(storage_options or {}))
|
| 254 |
+
if fs.exists(root):
|
| 255 |
+
fs.rm(root, recursive=True)
|
| 256 |
+
fs.makedirs(root, exist_ok=True)
|
| 257 |
+
fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode())
|
| 258 |
+
return LazyReferenceMapper(root, fs, **kwargs)
|
| 259 |
+
|
| 260 |
+
def listdir(self):
|
| 261 |
+
"""List top-level directories"""
|
| 262 |
+
dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z"))
|
| 263 |
+
return set(dirs)
|
| 264 |
+
|
| 265 |
+
def ls(self, path="", detail=True):
|
| 266 |
+
"""Shortcut file listings"""
|
| 267 |
+
path = path.rstrip("/")
|
| 268 |
+
pathdash = path + "/" if path else ""
|
| 269 |
+
dirnames = self.listdir()
|
| 270 |
+
dirs = [
|
| 271 |
+
d
|
| 272 |
+
for d in dirnames
|
| 273 |
+
if d.startswith(pathdash) and "/" not in d.lstrip(pathdash)
|
| 274 |
+
]
|
| 275 |
+
if dirs:
|
| 276 |
+
others = {
|
| 277 |
+
f
|
| 278 |
+
for f in chain(
|
| 279 |
+
[".zmetadata"],
|
| 280 |
+
(name for name in self.zmetadata),
|
| 281 |
+
(name for name in self._items),
|
| 282 |
+
)
|
| 283 |
+
if f.startswith(pathdash) and "/" not in f.lstrip(pathdash)
|
| 284 |
+
}
|
| 285 |
+
if detail is False:
|
| 286 |
+
others.update(dirs)
|
| 287 |
+
return sorted(others)
|
| 288 |
+
dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs]
|
| 289 |
+
fileinfo = [
|
| 290 |
+
{
|
| 291 |
+
"name": name,
|
| 292 |
+
"type": "file",
|
| 293 |
+
"size": len(
|
| 294 |
+
json.dumps(self.zmetadata[name])
|
| 295 |
+
if name in self.zmetadata
|
| 296 |
+
else self._items[name]
|
| 297 |
+
),
|
| 298 |
+
}
|
| 299 |
+
for name in others
|
| 300 |
+
]
|
| 301 |
+
return sorted(dirinfo + fileinfo, key=lambda s: s["name"])
|
| 302 |
+
field = path
|
| 303 |
+
others = set(
|
| 304 |
+
[name for name in self.zmetadata if name.startswith(f"{path}/")]
|
| 305 |
+
+ [name for name in self._items if name.startswith(f"{path}/")]
|
| 306 |
+
)
|
| 307 |
+
fileinfo = [
|
| 308 |
+
{
|
| 309 |
+
"name": name,
|
| 310 |
+
"type": "file",
|
| 311 |
+
"size": len(
|
| 312 |
+
json.dumps(self.zmetadata[name])
|
| 313 |
+
if name in self.zmetadata
|
| 314 |
+
else self._items[name]
|
| 315 |
+
),
|
| 316 |
+
}
|
| 317 |
+
for name in others
|
| 318 |
+
]
|
| 319 |
+
keys = self._keys_in_field(field)
|
| 320 |
+
|
| 321 |
+
if detail is False:
|
| 322 |
+
return list(others) + list(keys)
|
| 323 |
+
recs = self._generate_all_records(field)
|
| 324 |
+
recinfo = [
|
| 325 |
+
{"name": name, "type": "file", "size": rec[-1]}
|
| 326 |
+
for name, rec in zip(keys, recs)
|
| 327 |
+
if rec[0] # filters out path==None, deleted/missing
|
| 328 |
+
]
|
| 329 |
+
return fileinfo + recinfo
|
| 330 |
+
|
| 331 |
+
def _load_one_key(self, key):
|
| 332 |
+
"""Get the reference for one key
|
| 333 |
+
|
| 334 |
+
Returns bytes, one-element list or three-element list.
|
| 335 |
+
"""
|
| 336 |
+
if key in self._items:
|
| 337 |
+
return self._items[key]
|
| 338 |
+
elif key in self.zmetadata:
|
| 339 |
+
return json.dumps(self.zmetadata[key]).encode()
|
| 340 |
+
elif "/" not in key or self._is_meta(key):
|
| 341 |
+
raise KeyError(key)
|
| 342 |
+
field, _ = key.rsplit("/", 1)
|
| 343 |
+
record, ri, chunk_size = self._key_to_record(key)
|
| 344 |
+
maybe = self._items.get((field, record), {}).get(ri, False)
|
| 345 |
+
if maybe is None:
|
| 346 |
+
# explicitly deleted
|
| 347 |
+
raise KeyError
|
| 348 |
+
elif maybe:
|
| 349 |
+
return maybe
|
| 350 |
+
elif chunk_size == 0:
|
| 351 |
+
return b""
|
| 352 |
+
|
| 353 |
+
# Chunk keys can be loaded from row group and cached in LRU cache
|
| 354 |
+
try:
|
| 355 |
+
refs = self.open_refs(field, record)
|
| 356 |
+
except (ValueError, TypeError, FileNotFoundError) as exc:
|
| 357 |
+
raise KeyError(key) from exc
|
| 358 |
+
columns = ["path", "offset", "size", "raw"]
|
| 359 |
+
selection = [refs[c][ri] if c in refs else None for c in columns]
|
| 360 |
+
raw = selection[-1]
|
| 361 |
+
if raw is not None:
|
| 362 |
+
return raw
|
| 363 |
+
if selection[0] is None:
|
| 364 |
+
raise KeyError("This reference does not exist or has been deleted")
|
| 365 |
+
if selection[1:3] == [0, 0]:
|
| 366 |
+
# URL only
|
| 367 |
+
return selection[:1]
|
| 368 |
+
# URL, offset, size
|
| 369 |
+
return selection[:3]
|
| 370 |
+
|
| 371 |
+
def _key_to_record(self, key):
|
| 372 |
+
"""Details needed to construct a reference for one key"""
|
| 373 |
+
field, chunk = key.rsplit("/", 1)
|
| 374 |
+
chunk_sizes = self._get_chunk_sizes(field)
|
| 375 |
+
if len(chunk_sizes) == 0:
|
| 376 |
+
return 0, 0, 0
|
| 377 |
+
chunk_idx = [int(c) for c in chunk.split(".")]
|
| 378 |
+
chunk_number = ravel_multi_index(chunk_idx, chunk_sizes)
|
| 379 |
+
record = chunk_number // self.record_size
|
| 380 |
+
ri = chunk_number % self.record_size
|
| 381 |
+
return record, ri, len(chunk_sizes)
|
| 382 |
+
|
| 383 |
+
def _get_chunk_sizes(self, field):
|
| 384 |
+
"""The number of chunks along each axis for a given field"""
|
| 385 |
+
if field not in self.chunk_sizes:
|
| 386 |
+
zarray = self.zmetadata[f"{field}/.zarray"]
|
| 387 |
+
size_ratio = [
|
| 388 |
+
math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"])
|
| 389 |
+
]
|
| 390 |
+
self.chunk_sizes[field] = size_ratio or [1]
|
| 391 |
+
return self.chunk_sizes[field]
|
| 392 |
+
|
| 393 |
+
def _generate_record(self, field, record):
|
| 394 |
+
"""The references for a given parquet file of a given field"""
|
| 395 |
+
refs = self.open_refs(field, record)
|
| 396 |
+
it = iter(zip(*refs.values()))
|
| 397 |
+
if len(refs) == 3:
|
| 398 |
+
# All urls
|
| 399 |
+
return (list(t) for t in it)
|
| 400 |
+
elif len(refs) == 1:
|
| 401 |
+
# All raws
|
| 402 |
+
return refs["raw"]
|
| 403 |
+
else:
|
| 404 |
+
# Mix of urls and raws
|
| 405 |
+
return (list(t[:3]) if not t[3] else t[3] for t in it)
|
| 406 |
+
|
| 407 |
+
def _generate_all_records(self, field):
|
| 408 |
+
"""Load all the references within a field by iterating over the parquet files"""
|
| 409 |
+
nrec = 1
|
| 410 |
+
for ch in self._get_chunk_sizes(field):
|
| 411 |
+
nrec *= ch
|
| 412 |
+
nrec = math.ceil(nrec / self.record_size)
|
| 413 |
+
for record in range(nrec):
|
| 414 |
+
yield from self._generate_record(field, record)
|
| 415 |
+
|
| 416 |
+
def values(self):
|
| 417 |
+
return RefsValuesView(self)
|
| 418 |
+
|
| 419 |
+
def items(self):
|
| 420 |
+
return RefsItemsView(self)
|
| 421 |
+
|
| 422 |
+
def __hash__(self):
|
| 423 |
+
return id(self)
|
| 424 |
+
|
| 425 |
+
def __getitem__(self, key):
|
| 426 |
+
return self._load_one_key(key)
|
| 427 |
+
|
| 428 |
+
def __setitem__(self, key, value):
|
| 429 |
+
if "/" in key and not self._is_meta(key):
|
| 430 |
+
field, chunk = key.rsplit("/", 1)
|
| 431 |
+
record, i, _ = self._key_to_record(key)
|
| 432 |
+
subdict = self._items.setdefault((field, record), {})
|
| 433 |
+
subdict[i] = value
|
| 434 |
+
if len(subdict) == self.record_size:
|
| 435 |
+
self.write(field, record)
|
| 436 |
+
else:
|
| 437 |
+
# metadata or top-level
|
| 438 |
+
if hasattr(value, "to_bytes"):
|
| 439 |
+
val = value.to_bytes().decode()
|
| 440 |
+
elif isinstance(value, bytes):
|
| 441 |
+
val = value.decode()
|
| 442 |
+
else:
|
| 443 |
+
val = value
|
| 444 |
+
self._items[key] = val
|
| 445 |
+
new_value = json.loads(val)
|
| 446 |
+
self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value}
|
| 447 |
+
|
| 448 |
+
@staticmethod
|
| 449 |
+
def _is_meta(key):
|
| 450 |
+
return key.startswith(".z") or "/.z" in key
|
| 451 |
+
|
| 452 |
+
def __delitem__(self, key):
|
| 453 |
+
if key in self._items:
|
| 454 |
+
del self._items[key]
|
| 455 |
+
elif key in self.zmetadata:
|
| 456 |
+
del self.zmetadata[key]
|
| 457 |
+
else:
|
| 458 |
+
if "/" in key and not self._is_meta(key):
|
| 459 |
+
field, _ = key.rsplit("/", 1)
|
| 460 |
+
record, i, _ = self._key_to_record(key)
|
| 461 |
+
subdict = self._items.setdefault((field, record), {})
|
| 462 |
+
subdict[i] = None
|
| 463 |
+
if len(subdict) == self.record_size:
|
| 464 |
+
self.write(field, record)
|
| 465 |
+
else:
|
| 466 |
+
# metadata or top-level
|
| 467 |
+
self._items[key] = None
|
| 468 |
+
|
| 469 |
+
def write(self, field, record, base_url=None, storage_options=None):
|
| 470 |
+
# extra requirements if writing
|
| 471 |
+
import kerchunk.df
|
| 472 |
+
import numpy as np
|
| 473 |
+
import pandas as pd
|
| 474 |
+
|
| 475 |
+
partition = self._items[(field, record)]
|
| 476 |
+
original = False
|
| 477 |
+
if len(partition) < self.record_size:
|
| 478 |
+
try:
|
| 479 |
+
original = self.open_refs(field, record)
|
| 480 |
+
except OSError:
|
| 481 |
+
pass
|
| 482 |
+
|
| 483 |
+
if original:
|
| 484 |
+
paths = original["path"]
|
| 485 |
+
offsets = original["offset"]
|
| 486 |
+
sizes = original["size"]
|
| 487 |
+
raws = original["raw"]
|
| 488 |
+
else:
|
| 489 |
+
paths = np.full(self.record_size, np.nan, dtype="O")
|
| 490 |
+
offsets = np.zeros(self.record_size, dtype="int64")
|
| 491 |
+
sizes = np.zeros(self.record_size, dtype="int64")
|
| 492 |
+
raws = np.full(self.record_size, np.nan, dtype="O")
|
| 493 |
+
for j, data in partition.items():
|
| 494 |
+
if isinstance(data, list):
|
| 495 |
+
if (
|
| 496 |
+
str(paths.dtype) == "category"
|
| 497 |
+
and data[0] not in paths.dtype.categories
|
| 498 |
+
):
|
| 499 |
+
paths = paths.add_categories(data[0])
|
| 500 |
+
paths[j] = data[0]
|
| 501 |
+
if len(data) > 1:
|
| 502 |
+
offsets[j] = data[1]
|
| 503 |
+
sizes[j] = data[2]
|
| 504 |
+
elif data is None:
|
| 505 |
+
# delete
|
| 506 |
+
paths[j] = None
|
| 507 |
+
offsets[j] = 0
|
| 508 |
+
sizes[j] = 0
|
| 509 |
+
raws[j] = None
|
| 510 |
+
else:
|
| 511 |
+
# this is the only call into kerchunk, could remove
|
| 512 |
+
raws[j] = kerchunk.df._proc_raw(data)
|
| 513 |
+
# TODO: only save needed columns
|
| 514 |
+
df = pd.DataFrame(
|
| 515 |
+
{
|
| 516 |
+
"path": paths,
|
| 517 |
+
"offset": offsets,
|
| 518 |
+
"size": sizes,
|
| 519 |
+
"raw": raws,
|
| 520 |
+
},
|
| 521 |
+
copy=False,
|
| 522 |
+
)
|
| 523 |
+
if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh:
|
| 524 |
+
df["path"] = df["path"].astype("category")
|
| 525 |
+
object_encoding = {"raw": "bytes", "path": "utf8"}
|
| 526 |
+
has_nulls = ["path", "raw"]
|
| 527 |
+
|
| 528 |
+
fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq"
|
| 529 |
+
self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True)
|
| 530 |
+
|
| 531 |
+
if self.engine == "pyarrow":
|
| 532 |
+
df_backend_kwargs = {"write_statistics": False}
|
| 533 |
+
elif self.engine == "fastparquet":
|
| 534 |
+
df_backend_kwargs = {
|
| 535 |
+
"stats": False,
|
| 536 |
+
"object_encoding": object_encoding,
|
| 537 |
+
"has_nulls": has_nulls,
|
| 538 |
+
}
|
| 539 |
+
else:
|
| 540 |
+
raise NotImplementedError(f"{self.engine} not supported")
|
| 541 |
+
df.to_parquet(
|
| 542 |
+
fn,
|
| 543 |
+
engine=self.engine,
|
| 544 |
+
storage_options=storage_options
|
| 545 |
+
or getattr(self.fs, "storage_options", None),
|
| 546 |
+
compression="zstd",
|
| 547 |
+
index=False,
|
| 548 |
+
**df_backend_kwargs,
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
partition.clear()
|
| 552 |
+
self._items.pop((field, record))
|
| 553 |
+
|
| 554 |
+
def flush(self, base_url=None, storage_options=None):
|
| 555 |
+
"""Output any modified or deleted keys
|
| 556 |
+
|
| 557 |
+
Parameters
|
| 558 |
+
----------
|
| 559 |
+
base_url: str
|
| 560 |
+
Location of the output
|
| 561 |
+
"""
|
| 562 |
+
|
| 563 |
+
# write what we have so far and clear sub chunks
|
| 564 |
+
for thing in list(self._items):
|
| 565 |
+
if isinstance(thing, tuple):
|
| 566 |
+
field, record = thing
|
| 567 |
+
self.write(
|
| 568 |
+
field,
|
| 569 |
+
record,
|
| 570 |
+
base_url=base_url,
|
| 571 |
+
storage_options=storage_options,
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
# gather .zmetadata from self._items and write that too
|
| 575 |
+
for k in list(self._items):
|
| 576 |
+
if k != ".zmetadata" and ".z" in k:
|
| 577 |
+
self.zmetadata[k] = json.loads(self._items.pop(k))
|
| 578 |
+
met = {"metadata": self.zmetadata, "record_size": self.record_size}
|
| 579 |
+
self._items.clear()
|
| 580 |
+
self._items[".zmetadata"] = json.dumps(met).encode()
|
| 581 |
+
self.fs.pipe(
|
| 582 |
+
"/".join([base_url or self.out_root, ".zmetadata"]),
|
| 583 |
+
self._items[".zmetadata"],
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
# TODO: only clear those that we wrote to?
|
| 587 |
+
self.open_refs.cache_clear()
|
| 588 |
+
|
| 589 |
+
def __len__(self):
|
| 590 |
+
# Caveat: This counts expected references, not actual - but is fast
|
| 591 |
+
count = 0
|
| 592 |
+
for field in self.listdir():
|
| 593 |
+
if field.startswith("."):
|
| 594 |
+
count += 1
|
| 595 |
+
else:
|
| 596 |
+
count += math.prod(self._get_chunk_sizes(field))
|
| 597 |
+
count += len(self.zmetadata) # all metadata keys
|
| 598 |
+
# any other files not in reference partitions
|
| 599 |
+
count += sum(1 for _ in self._items if not isinstance(_, tuple))
|
| 600 |
+
return count
|
| 601 |
+
|
| 602 |
+
def __iter__(self):
|
| 603 |
+
# Caveat: returns only existing keys, so the number of these does not
|
| 604 |
+
# match len(self)
|
| 605 |
+
metas = set(self.zmetadata)
|
| 606 |
+
metas.update(self._items)
|
| 607 |
+
for bit in metas:
|
| 608 |
+
if isinstance(bit, str):
|
| 609 |
+
yield bit
|
| 610 |
+
for field in self.listdir():
|
| 611 |
+
for k in self._keys_in_field(field):
|
| 612 |
+
if k in self:
|
| 613 |
+
yield k
|
| 614 |
+
|
| 615 |
+
def __contains__(self, item):
|
| 616 |
+
try:
|
| 617 |
+
self._load_one_key(item)
|
| 618 |
+
return True
|
| 619 |
+
except KeyError:
|
| 620 |
+
return False
|
| 621 |
+
|
| 622 |
+
def _keys_in_field(self, field):
|
| 623 |
+
"""List key names in given field
|
| 624 |
+
|
| 625 |
+
Produces strings like "field/x.y" appropriate from the chunking of the array
|
| 626 |
+
"""
|
| 627 |
+
chunk_sizes = self._get_chunk_sizes(field)
|
| 628 |
+
if len(chunk_sizes) == 0:
|
| 629 |
+
yield field + "/0"
|
| 630 |
+
return
|
| 631 |
+
inds = itertools.product(*(range(i) for i in chunk_sizes))
|
| 632 |
+
for ind in inds:
|
| 633 |
+
yield field + "/" + ".".join([str(c) for c in ind])
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
class ReferenceFileSystem(AsyncFileSystem):
|
| 637 |
+
"""View byte ranges of some other file as a file system
|
| 638 |
+
Initial version: single file system target, which must support
|
| 639 |
+
async, and must allow start and end args in _cat_file. Later versions
|
| 640 |
+
may allow multiple arbitrary URLs for the targets.
|
| 641 |
+
This FileSystem is read-only. It is designed to be used with async
|
| 642 |
+
targets (for now). We do not get original file details from the target FS.
|
| 643 |
+
Configuration is by passing a dict of references at init, or a URL to
|
| 644 |
+
a JSON file containing the same; this dict
|
| 645 |
+
can also contain concrete data for some set of paths.
|
| 646 |
+
Reference dict format:
|
| 647 |
+
{path0: bytes_data, path1: (target_url, offset, size)}
|
| 648 |
+
https://github.com/fsspec/kerchunk/blob/main/README.md
|
| 649 |
+
|
| 650 |
+
simple_references: if True (default), no jinja interpreting is done,
|
| 651 |
+
which is the safe option.
|
| 652 |
+
"""
|
| 653 |
+
|
| 654 |
+
protocol = "reference"
|
| 655 |
+
cachable = False
|
| 656 |
+
|
| 657 |
+
def __init__(
|
| 658 |
+
self,
|
| 659 |
+
fo,
|
| 660 |
+
target=None,
|
| 661 |
+
ref_storage_args=None,
|
| 662 |
+
target_protocol=None,
|
| 663 |
+
target_options=None,
|
| 664 |
+
remote_protocol=None,
|
| 665 |
+
remote_options=None,
|
| 666 |
+
fs=None,
|
| 667 |
+
template_overrides=None,
|
| 668 |
+
simple_templates=True,
|
| 669 |
+
max_gap=64_000,
|
| 670 |
+
max_block=256_000_000,
|
| 671 |
+
cache_size=128,
|
| 672 |
+
**kwargs,
|
| 673 |
+
):
|
| 674 |
+
"""
|
| 675 |
+
Parameters
|
| 676 |
+
----------
|
| 677 |
+
fo : dict or str
|
| 678 |
+
The set of references to use for this instance, with a structure as above.
|
| 679 |
+
If str referencing a JSON file, will use fsspec.open, in conjunction
|
| 680 |
+
with target_options and target_protocol to open and parse JSON at this
|
| 681 |
+
location. If a directory, then assume references are a set of parquet
|
| 682 |
+
files to be loaded lazily.
|
| 683 |
+
target : str
|
| 684 |
+
For any references having target_url as None, this is the default file
|
| 685 |
+
target to use
|
| 686 |
+
ref_storage_args : dict
|
| 687 |
+
If references is a str, use these kwargs for loading the JSON file.
|
| 688 |
+
Deprecated: use target_options instead.
|
| 689 |
+
target_protocol : str
|
| 690 |
+
Used for loading the reference file, if it is a path. If None, protocol
|
| 691 |
+
will be derived from the given path
|
| 692 |
+
target_options : dict
|
| 693 |
+
Extra FS options for loading the reference file ``fo``, if given as a path
|
| 694 |
+
remote_protocol : str
|
| 695 |
+
The protocol of the filesystem on which the references will be evaluated
|
| 696 |
+
(unless fs is provided). If not given, will be derived from the first
|
| 697 |
+
URL that has a protocol in the templates or in the references, in that
|
| 698 |
+
order.
|
| 699 |
+
remote_options : dict
|
| 700 |
+
kwargs to go with remote_protocol
|
| 701 |
+
fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict))
|
| 702 |
+
Directly provide a file system(s):
|
| 703 |
+
- a single filesystem instance
|
| 704 |
+
- a dict of protocol:filesystem, where each value is either a filesystem
|
| 705 |
+
instance, or a dict of kwargs that can be used to create in
|
| 706 |
+
instance for the given protocol
|
| 707 |
+
|
| 708 |
+
If this is given, remote_options and remote_protocol are ignored.
|
| 709 |
+
template_overrides : dict
|
| 710 |
+
Swap out any templates in the references file with these - useful for
|
| 711 |
+
testing.
|
| 712 |
+
simple_templates: bool
|
| 713 |
+
Whether templates can be processed with simple replace (True) or if
|
| 714 |
+
jinja is needed (False, much slower). All reference sets produced by
|
| 715 |
+
``kerchunk`` are simple in this sense, but the spec allows for complex.
|
| 716 |
+
max_gap, max_block: int
|
| 717 |
+
For merging multiple concurrent requests to the same remote file.
|
| 718 |
+
Neighboring byte ranges will only be merged when their
|
| 719 |
+
inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0
|
| 720 |
+
to only merge when it requires no extra bytes. Pass a negative
|
| 721 |
+
number to disable merging, appropriate for local target files.
|
| 722 |
+
Neighboring byte ranges will only be merged when the size of
|
| 723 |
+
the aggregated range is <= ``max_block``. Default is 256MB.
|
| 724 |
+
cache_size : int
|
| 725 |
+
Maximum size of LRU cache, where cache_size*record_size denotes
|
| 726 |
+
the total number of references that can be loaded in memory at once.
|
| 727 |
+
Only used for lazily loaded references.
|
| 728 |
+
kwargs : passed to parent class
|
| 729 |
+
"""
|
| 730 |
+
super().__init__(**kwargs)
|
| 731 |
+
self.target = target
|
| 732 |
+
self.template_overrides = template_overrides
|
| 733 |
+
self.simple_templates = simple_templates
|
| 734 |
+
self.templates = {}
|
| 735 |
+
self.fss = {}
|
| 736 |
+
self._dircache = {}
|
| 737 |
+
self.max_gap = max_gap
|
| 738 |
+
self.max_block = max_block
|
| 739 |
+
if isinstance(fo, str):
|
| 740 |
+
dic = dict(
|
| 741 |
+
**(ref_storage_args or target_options or {}), protocol=target_protocol
|
| 742 |
+
)
|
| 743 |
+
ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic)
|
| 744 |
+
if ".json" not in fo2 and (
|
| 745 |
+
fo.endswith(("parq", "parquet", "/")) or ref_fs.isdir(fo2)
|
| 746 |
+
):
|
| 747 |
+
# Lazy parquet refs
|
| 748 |
+
logger.info("Open lazy reference dict from URL %s", fo)
|
| 749 |
+
self.references = LazyReferenceMapper(
|
| 750 |
+
fo2,
|
| 751 |
+
fs=ref_fs,
|
| 752 |
+
cache_size=cache_size,
|
| 753 |
+
)
|
| 754 |
+
else:
|
| 755 |
+
# text JSON
|
| 756 |
+
with fsspec.open(fo, "rb", **dic) as f:
|
| 757 |
+
logger.info("Read reference from URL %s", fo)
|
| 758 |
+
text = json.load(f)
|
| 759 |
+
self._process_references(text, template_overrides)
|
| 760 |
+
else:
|
| 761 |
+
# dictionaries
|
| 762 |
+
self._process_references(fo, template_overrides)
|
| 763 |
+
if isinstance(fs, dict):
|
| 764 |
+
self.fss = {
|
| 765 |
+
k: (
|
| 766 |
+
fsspec.filesystem(k.split(":", 1)[0], **opts)
|
| 767 |
+
if isinstance(opts, dict)
|
| 768 |
+
else opts
|
| 769 |
+
)
|
| 770 |
+
for k, opts in fs.items()
|
| 771 |
+
}
|
| 772 |
+
if None not in self.fss:
|
| 773 |
+
self.fss[None] = filesystem("file")
|
| 774 |
+
return
|
| 775 |
+
if fs is not None:
|
| 776 |
+
# single remote FS
|
| 777 |
+
remote_protocol = (
|
| 778 |
+
fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol
|
| 779 |
+
)
|
| 780 |
+
self.fss[remote_protocol] = fs
|
| 781 |
+
|
| 782 |
+
if remote_protocol is None:
|
| 783 |
+
# get single protocol from any templates
|
| 784 |
+
for ref in self.templates.values():
|
| 785 |
+
if callable(ref):
|
| 786 |
+
ref = ref()
|
| 787 |
+
protocol, _ = fsspec.core.split_protocol(ref)
|
| 788 |
+
if protocol and protocol not in self.fss:
|
| 789 |
+
fs = filesystem(protocol, **(remote_options or {}))
|
| 790 |
+
self.fss[protocol] = fs
|
| 791 |
+
if remote_protocol is None:
|
| 792 |
+
# get single protocol from references
|
| 793 |
+
# TODO: warning here, since this can be very expensive?
|
| 794 |
+
for ref in self.references.values():
|
| 795 |
+
if callable(ref):
|
| 796 |
+
ref = ref()
|
| 797 |
+
if isinstance(ref, list) and ref[0]:
|
| 798 |
+
protocol, _ = fsspec.core.split_protocol(ref[0])
|
| 799 |
+
if protocol not in self.fss:
|
| 800 |
+
fs = filesystem(protocol, **(remote_options or {}))
|
| 801 |
+
self.fss[protocol] = fs
|
| 802 |
+
# only use first remote URL
|
| 803 |
+
break
|
| 804 |
+
|
| 805 |
+
if remote_protocol and remote_protocol not in self.fss:
|
| 806 |
+
fs = filesystem(remote_protocol, **(remote_options or {}))
|
| 807 |
+
self.fss[remote_protocol] = fs
|
| 808 |
+
|
| 809 |
+
self.fss[None] = fs or filesystem("file") # default one
|
| 810 |
+
# Wrap any non-async filesystems to ensure async methods are available below
|
| 811 |
+
for k, f in self.fss.items():
|
| 812 |
+
if not f.async_impl:
|
| 813 |
+
self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous)
|
| 814 |
+
elif self.asynchronous ^ f.asynchronous:
|
| 815 |
+
raise ValueError(
|
| 816 |
+
"Reference-FS's target filesystem must have same value "
|
| 817 |
+
"of asynchronous"
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
+
def _cat_common(self, path, start=None, end=None):
|
| 821 |
+
path = self._strip_protocol(path)
|
| 822 |
+
logger.debug(f"cat: {path}")
|
| 823 |
+
try:
|
| 824 |
+
part = self.references[path]
|
| 825 |
+
except KeyError as exc:
|
| 826 |
+
raise FileNotFoundError(path) from exc
|
| 827 |
+
if isinstance(part, str):
|
| 828 |
+
part = part.encode()
|
| 829 |
+
if hasattr(part, "to_bytes"):
|
| 830 |
+
part = part.to_bytes()
|
| 831 |
+
if isinstance(part, bytes):
|
| 832 |
+
logger.debug(f"Reference: {path}, type bytes")
|
| 833 |
+
return _inline_data(part), None, None
|
| 834 |
+
|
| 835 |
+
if len(part) == 1:
|
| 836 |
+
logger.debug(f"Reference: {path}, whole file => {part}")
|
| 837 |
+
url = part[0]
|
| 838 |
+
start1, end1 = start, end
|
| 839 |
+
else:
|
| 840 |
+
url, start0, size = part
|
| 841 |
+
logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}")
|
| 842 |
+
end0 = start0 + size
|
| 843 |
+
|
| 844 |
+
# Resolve offsets like slicing the part, so they never reach target
|
| 845 |
+
# bytes outside the referenced range.
|
| 846 |
+
if start is not None:
|
| 847 |
+
if start >= 0:
|
| 848 |
+
start1 = min(start0 + start, end0)
|
| 849 |
+
else:
|
| 850 |
+
start1 = max(end0 + start, start0)
|
| 851 |
+
else:
|
| 852 |
+
start1 = start0
|
| 853 |
+
if end is not None:
|
| 854 |
+
if end >= 0:
|
| 855 |
+
end1 = min(start0 + end, end0)
|
| 856 |
+
else:
|
| 857 |
+
end1 = max(end0 + end, start0)
|
| 858 |
+
else:
|
| 859 |
+
end1 = end0
|
| 860 |
+
if url is None:
|
| 861 |
+
url = self.target
|
| 862 |
+
return url, start1, end1
|
| 863 |
+
|
| 864 |
+
async def _cat_file(self, path, start=None, end=None, **kwargs):
|
| 865 |
+
part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
|
| 866 |
+
if isinstance(part_or_url, bytes):
|
| 867 |
+
return part_or_url[start:end]
|
| 868 |
+
protocol, _ = split_protocol(part_or_url)
|
| 869 |
+
try:
|
| 870 |
+
return await self.fss[protocol]._cat_file(
|
| 871 |
+
part_or_url, start=start0, end=end0
|
| 872 |
+
)
|
| 873 |
+
except Exception as e:
|
| 874 |
+
raise ReferenceNotReachable(path, part_or_url) from e
|
| 875 |
+
|
| 876 |
+
def cat_file(self, path, start=None, end=None, **kwargs):
|
| 877 |
+
part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
|
| 878 |
+
if isinstance(part_or_url, bytes):
|
| 879 |
+
return part_or_url[start:end]
|
| 880 |
+
protocol, _ = split_protocol(part_or_url)
|
| 881 |
+
try:
|
| 882 |
+
return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0)
|
| 883 |
+
except Exception as e:
|
| 884 |
+
raise ReferenceNotReachable(path, part_or_url) from e
|
| 885 |
+
|
| 886 |
+
def pipe_file(self, path, value, **_):
|
| 887 |
+
"""Temporarily add binary data or reference as a file"""
|
| 888 |
+
self.references[path] = value
|
| 889 |
+
|
| 890 |
+
async def _get_file(self, rpath, lpath, **kwargs):
|
| 891 |
+
if self.isdir(rpath):
|
| 892 |
+
return os.makedirs(lpath, exist_ok=True)
|
| 893 |
+
data = await self._cat_file(rpath)
|
| 894 |
+
with open(lpath, "wb") as f:
|
| 895 |
+
f.write(data)
|
| 896 |
+
|
| 897 |
+
def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs):
|
| 898 |
+
if self.isdir(rpath):
|
| 899 |
+
return os.makedirs(lpath, exist_ok=True)
|
| 900 |
+
data = self.cat_file(rpath, **kwargs)
|
| 901 |
+
callback.set_size(len(data))
|
| 902 |
+
if isfilelike(lpath):
|
| 903 |
+
lpath.write(data)
|
| 904 |
+
else:
|
| 905 |
+
with open(lpath, "wb") as f:
|
| 906 |
+
f.write(data)
|
| 907 |
+
callback.absolute_update(len(data))
|
| 908 |
+
|
| 909 |
+
def get(self, rpath, lpath, recursive=False, maxdepth=None, **kwargs):
|
| 910 |
+
if recursive:
|
| 911 |
+
# trigger directory build
|
| 912 |
+
self.ls("")
|
| 913 |
+
rpath = self.expand_path(rpath, recursive=recursive, maxdepth=maxdepth)
|
| 914 |
+
fs = fsspec.filesystem("file", auto_mkdir=True)
|
| 915 |
+
targets = other_paths(rpath, lpath)
|
| 916 |
+
if isinstance(lpath, str):
|
| 917 |
+
# The names came from the source listing; ".." in one of them
|
| 918 |
+
# would otherwise place the copy above the destination. When
|
| 919 |
+
# lpath is a list the caller named every destination itself.
|
| 920 |
+
check_contained(lpath, targets)
|
| 921 |
+
if recursive:
|
| 922 |
+
data = self.cat([r for r in rpath if not self.isdir(r)])
|
| 923 |
+
else:
|
| 924 |
+
data = self.cat(rpath)
|
| 925 |
+
for remote, local in zip(rpath, targets):
|
| 926 |
+
if remote in data:
|
| 927 |
+
fs.pipe_file(local, data[remote])
|
| 928 |
+
|
| 929 |
+
def cat(self, path, recursive=False, on_error="raise", **kwargs):
|
| 930 |
+
if isinstance(path, str) and recursive:
|
| 931 |
+
raise NotImplementedError
|
| 932 |
+
if isinstance(path, list) and (recursive or any("*" in p for p in path)):
|
| 933 |
+
raise NotImplementedError
|
| 934 |
+
# TODO: if references is lazy, pre-fetch all paths in batch before access
|
| 935 |
+
proto_dict = _protocol_groups(path, self.references)
|
| 936 |
+
out = {}
|
| 937 |
+
for proto, paths in proto_dict.items():
|
| 938 |
+
fs = self.fss[proto]
|
| 939 |
+
urls, starts, ends, valid_paths = [], [], [], []
|
| 940 |
+
for p in paths:
|
| 941 |
+
# find references or label not-found. Early exit if any not
|
| 942 |
+
# found and on_error is "raise"
|
| 943 |
+
try:
|
| 944 |
+
u, s, e = self._cat_common(p)
|
| 945 |
+
if not isinstance(u, (bytes, str)):
|
| 946 |
+
# nan/None from parquet
|
| 947 |
+
continue
|
| 948 |
+
except FileNotFoundError as err:
|
| 949 |
+
if on_error == "raise":
|
| 950 |
+
raise
|
| 951 |
+
if on_error != "omit":
|
| 952 |
+
out[p] = err
|
| 953 |
+
else:
|
| 954 |
+
urls.append(u)
|
| 955 |
+
starts.append(s)
|
| 956 |
+
ends.append(e)
|
| 957 |
+
valid_paths.append(p)
|
| 958 |
+
|
| 959 |
+
# process references into form for merging
|
| 960 |
+
urls2 = []
|
| 961 |
+
starts2 = []
|
| 962 |
+
ends2 = []
|
| 963 |
+
paths2 = []
|
| 964 |
+
whole_files = set()
|
| 965 |
+
for u, s, e, p in zip(urls, starts, ends, valid_paths):
|
| 966 |
+
if isinstance(u, bytes):
|
| 967 |
+
# data
|
| 968 |
+
out[p] = u
|
| 969 |
+
elif s is None:
|
| 970 |
+
# whole file - limits are None, None, but no further
|
| 971 |
+
# entries take for this file
|
| 972 |
+
whole_files.add(u)
|
| 973 |
+
urls2.append(u)
|
| 974 |
+
starts2.append(s)
|
| 975 |
+
ends2.append(e)
|
| 976 |
+
paths2.append(p)
|
| 977 |
+
for u, s, e, p in zip(urls, starts, ends, valid_paths):
|
| 978 |
+
# second run to account for files that are to be loaded whole
|
| 979 |
+
if s is not None and u not in whole_files:
|
| 980 |
+
urls2.append(u)
|
| 981 |
+
starts2.append(s)
|
| 982 |
+
ends2.append(e)
|
| 983 |
+
paths2.append(p)
|
| 984 |
+
|
| 985 |
+
# merge and fetch consolidated ranges
|
| 986 |
+
new_paths, new_starts, new_ends = merge_offset_ranges(
|
| 987 |
+
list(urls2),
|
| 988 |
+
list(starts2),
|
| 989 |
+
list(ends2),
|
| 990 |
+
sort=True,
|
| 991 |
+
max_gap=self.max_gap,
|
| 992 |
+
max_block=self.max_block,
|
| 993 |
+
)
|
| 994 |
+
bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends)
|
| 995 |
+
|
| 996 |
+
# unbundle from merged bytes - simple approach
|
| 997 |
+
for u, s, e, p in zip(urls, starts, ends, valid_paths):
|
| 998 |
+
if p in out:
|
| 999 |
+
continue # was bytes, already handled
|
| 1000 |
+
for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out):
|
| 1001 |
+
if np == u and (ns is None or ne is None):
|
| 1002 |
+
if isinstance(b, Exception):
|
| 1003 |
+
out[p] = b
|
| 1004 |
+
else:
|
| 1005 |
+
out[p] = b[s:e]
|
| 1006 |
+
elif np == u and s >= ns and e <= ne:
|
| 1007 |
+
if isinstance(b, Exception):
|
| 1008 |
+
out[p] = b
|
| 1009 |
+
else:
|
| 1010 |
+
out[p] = b[s - ns : (e - ne) or None]
|
| 1011 |
+
|
| 1012 |
+
for k, v in out.copy().items():
|
| 1013 |
+
# these were valid references, but fetch failed, so transform exc
|
| 1014 |
+
if isinstance(v, Exception) and k in self.references:
|
| 1015 |
+
ex = out[k]
|
| 1016 |
+
new_ex = ReferenceNotReachable(k, self.references[k])
|
| 1017 |
+
new_ex.__cause__ = ex
|
| 1018 |
+
if on_error == "raise":
|
| 1019 |
+
raise new_ex
|
| 1020 |
+
elif on_error != "omit":
|
| 1021 |
+
out[k] = new_ex
|
| 1022 |
+
else:
|
| 1023 |
+
del out[k]
|
| 1024 |
+
|
| 1025 |
+
if len(out) == 1 and isinstance(path, str) and "*" not in path:
|
| 1026 |
+
return _first(out)
|
| 1027 |
+
return out
|
| 1028 |
+
|
| 1029 |
+
def _process_references(self, references, template_overrides=None):
|
| 1030 |
+
vers = references.get("version", None)
|
| 1031 |
+
if vers is None:
|
| 1032 |
+
self._process_references0(references)
|
| 1033 |
+
elif vers == 1:
|
| 1034 |
+
self._process_references1(references, template_overrides=template_overrides)
|
| 1035 |
+
else:
|
| 1036 |
+
raise ValueError(f"Unknown reference spec version: {vers}")
|
| 1037 |
+
# TODO: we make dircache by iterating over all entries, but for Spec >= 1,
|
| 1038 |
+
# can replace with programmatic. Is it even needed for mapper interface?
|
| 1039 |
+
|
| 1040 |
+
def _process_references0(self, references):
|
| 1041 |
+
"""Make reference dict for Spec Version 0"""
|
| 1042 |
+
if isinstance(references, dict):
|
| 1043 |
+
# do not do this for lazy/parquet backend, which will not make dicts,
|
| 1044 |
+
# but must remain writable in the original object
|
| 1045 |
+
references = {
|
| 1046 |
+
key: json.dumps(val) if isinstance(val, dict) else val
|
| 1047 |
+
for key, val in references.items()
|
| 1048 |
+
}
|
| 1049 |
+
self.references = references
|
| 1050 |
+
|
| 1051 |
+
def _process_references1(self, references, template_overrides=None):
|
| 1052 |
+
if not self.simple_templates or self.templates:
|
| 1053 |
+
import jinja2.sandbox
|
| 1054 |
+
self.references = {}
|
| 1055 |
+
self._process_templates(references.get("templates", {}))
|
| 1056 |
+
|
| 1057 |
+
@lru_cache(1000)
|
| 1058 |
+
def _render_jinja(u):
|
| 1059 |
+
return (
|
| 1060 |
+
jinja2.sandbox.SandboxedEnvironment()
|
| 1061 |
+
.from_string(u)
|
| 1062 |
+
.render(**self.templates)
|
| 1063 |
+
)
|
| 1064 |
+
|
| 1065 |
+
for k, v in references.get("refs", {}).items():
|
| 1066 |
+
if isinstance(v, str):
|
| 1067 |
+
if v.startswith("base64:"):
|
| 1068 |
+
self.references[k] = base64.b64decode(v[7:])
|
| 1069 |
+
self.references[k] = v
|
| 1070 |
+
elif isinstance(v, dict):
|
| 1071 |
+
self.references[k] = json.dumps(v)
|
| 1072 |
+
elif self.templates:
|
| 1073 |
+
u = v[0]
|
| 1074 |
+
if "{{" in u:
|
| 1075 |
+
if self.simple_templates:
|
| 1076 |
+
u = (
|
| 1077 |
+
u.replace("{{", "{")
|
| 1078 |
+
.replace("}}", "}")
|
| 1079 |
+
.format(**self.templates)
|
| 1080 |
+
)
|
| 1081 |
+
else:
|
| 1082 |
+
u = _render_jinja(u)
|
| 1083 |
+
self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]]
|
| 1084 |
+
else:
|
| 1085 |
+
self.references[k] = v
|
| 1086 |
+
self.references.update(self._process_gen(references.get("gen", [])))
|
| 1087 |
+
|
| 1088 |
+
def _process_templates(self, tmp):
|
| 1089 |
+
self.templates = {}
|
| 1090 |
+
if self.template_overrides is not None:
|
| 1091 |
+
tmp.update(self.template_overrides)
|
| 1092 |
+
for k, v in tmp.items():
|
| 1093 |
+
if "{{" in v:
|
| 1094 |
+
import jinja2.sandbox
|
| 1095 |
+
|
| 1096 |
+
self.templates[k] = (
|
| 1097 |
+
lambda temp=v, **kwargs: jinja2.sandbox.SandboxedEnvironment()
|
| 1098 |
+
.from_string(temp)
|
| 1099 |
+
.render(**kwargs)
|
| 1100 |
+
)
|
| 1101 |
+
else:
|
| 1102 |
+
self.templates[k] = v
|
| 1103 |
+
|
| 1104 |
+
def _process_gen(self, gens):
|
| 1105 |
+
out = {}
|
| 1106 |
+
if self.simple_templates:
|
| 1107 |
+
return out
|
| 1108 |
+
for gen in gens:
|
| 1109 |
+
dimension = {
|
| 1110 |
+
k: (
|
| 1111 |
+
v
|
| 1112 |
+
if isinstance(v, list)
|
| 1113 |
+
else range(v.get("start", 0), v["stop"], v.get("step", 1))
|
| 1114 |
+
)
|
| 1115 |
+
for k, v in gen["dimensions"].items()
|
| 1116 |
+
}
|
| 1117 |
+
products = (
|
| 1118 |
+
dict(zip(dimension.keys(), values))
|
| 1119 |
+
for values in itertools.product(*dimension.values())
|
| 1120 |
+
)
|
| 1121 |
+
for pr in products:
|
| 1122 |
+
import jinja2.sandbox
|
| 1123 |
+
|
| 1124 |
+
key = (
|
| 1125 |
+
jinja2.sandbox.SandboxedEnvironment()
|
| 1126 |
+
.from_string(gen["key"])
|
| 1127 |
+
.render(**pr, **self.templates)
|
| 1128 |
+
)
|
| 1129 |
+
url = (
|
| 1130 |
+
jinja2.sandbox.SandboxedEnvironment()
|
| 1131 |
+
.from_string(gen["url"])
|
| 1132 |
+
.render(**pr, **self.templates)
|
| 1133 |
+
)
|
| 1134 |
+
if ("offset" in gen) and ("length" in gen):
|
| 1135 |
+
offset = int(
|
| 1136 |
+
jinja2.sandbox.SandboxedEnvironment()
|
| 1137 |
+
.from_string(gen["offset"])
|
| 1138 |
+
.render(**pr, **self.templates)
|
| 1139 |
+
)
|
| 1140 |
+
length = int(
|
| 1141 |
+
jinja2.sandbox.SandboxedEnvironment()
|
| 1142 |
+
.from_string(gen["length"])
|
| 1143 |
+
.render(**pr, **self.templates)
|
| 1144 |
+
)
|
| 1145 |
+
out[key] = [url, offset, length]
|
| 1146 |
+
elif ("offset" in gen) ^ ("length" in gen):
|
| 1147 |
+
raise ValueError(
|
| 1148 |
+
"Both 'offset' and 'length' are required for a "
|
| 1149 |
+
"reference generator entry if either is provided."
|
| 1150 |
+
)
|
| 1151 |
+
else:
|
| 1152 |
+
out[key] = [url]
|
| 1153 |
+
return out
|
| 1154 |
+
|
| 1155 |
+
def _dircache_from_items(self):
|
| 1156 |
+
self.dircache = {"": []}
|
| 1157 |
+
it = self.references.items()
|
| 1158 |
+
for path, part in it:
|
| 1159 |
+
if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"):
|
| 1160 |
+
size = len(_inline_data(part))
|
| 1161 |
+
elif len(part) == 1:
|
| 1162 |
+
size = None
|
| 1163 |
+
else:
|
| 1164 |
+
_, _, size = part
|
| 1165 |
+
par = path.rsplit("/", 1)[0] if "/" in path else ""
|
| 1166 |
+
par0 = par
|
| 1167 |
+
subdirs = [par0]
|
| 1168 |
+
while par0 and par0 not in self.dircache:
|
| 1169 |
+
# collect parent directories
|
| 1170 |
+
par0 = self._parent(par0)
|
| 1171 |
+
subdirs.append(par0)
|
| 1172 |
+
|
| 1173 |
+
subdirs.reverse()
|
| 1174 |
+
for parent, child in zip(subdirs, subdirs[1:]):
|
| 1175 |
+
# register newly discovered directories
|
| 1176 |
+
assert child not in self.dircache
|
| 1177 |
+
assert parent in self.dircache
|
| 1178 |
+
self.dircache[parent].append(
|
| 1179 |
+
{"name": child, "type": "directory", "size": 0}
|
| 1180 |
+
)
|
| 1181 |
+
self.dircache[child] = []
|
| 1182 |
+
|
| 1183 |
+
self.dircache[par].append({"name": path, "type": "file", "size": size})
|
| 1184 |
+
|
| 1185 |
+
def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs):
|
| 1186 |
+
part_or_url, start0, end0 = self._cat_common(path)
|
| 1187 |
+
# This logic is kept outside `ReferenceFile` to avoid unnecessary redirection.
|
| 1188 |
+
# That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`.
|
| 1189 |
+
if isinstance(part_or_url, bytes):
|
| 1190 |
+
return io.BytesIO(part_or_url[start0:end0])
|
| 1191 |
+
|
| 1192 |
+
protocol, _ = split_protocol(part_or_url)
|
| 1193 |
+
if start0 is None and end0 is None:
|
| 1194 |
+
return self.fss[protocol]._open(
|
| 1195 |
+
part_or_url,
|
| 1196 |
+
mode,
|
| 1197 |
+
block_size=block_size,
|
| 1198 |
+
cache_options=cache_options,
|
| 1199 |
+
**kwargs,
|
| 1200 |
+
)
|
| 1201 |
+
|
| 1202 |
+
return ReferenceFile(
|
| 1203 |
+
self,
|
| 1204 |
+
path,
|
| 1205 |
+
mode,
|
| 1206 |
+
block_size=block_size,
|
| 1207 |
+
cache_options=cache_options,
|
| 1208 |
+
**kwargs,
|
| 1209 |
+
)
|
| 1210 |
+
|
| 1211 |
+
def ls(self, path, detail=True, **kwargs):
|
| 1212 |
+
logger.debug("list %s", path)
|
| 1213 |
+
path = self._strip_protocol(path)
|
| 1214 |
+
if isinstance(self.references, LazyReferenceMapper):
|
| 1215 |
+
try:
|
| 1216 |
+
return self.references.ls(path, detail)
|
| 1217 |
+
except KeyError:
|
| 1218 |
+
pass
|
| 1219 |
+
raise FileNotFoundError(f"'{path}' is not a known key")
|
| 1220 |
+
if not self.dircache:
|
| 1221 |
+
self._dircache_from_items()
|
| 1222 |
+
out = self._ls_from_cache(path)
|
| 1223 |
+
if out is None:
|
| 1224 |
+
raise FileNotFoundError(path)
|
| 1225 |
+
if detail:
|
| 1226 |
+
return out
|
| 1227 |
+
return [o["name"] for o in out]
|
| 1228 |
+
|
| 1229 |
+
def exists(self, path, **kwargs): # overwrite auto-sync version
|
| 1230 |
+
return self.isdir(path) or self.isfile(path)
|
| 1231 |
+
|
| 1232 |
+
def isdir(self, path): # overwrite auto-sync version
|
| 1233 |
+
if self.dircache:
|
| 1234 |
+
return path in self.dircache
|
| 1235 |
+
elif isinstance(self.references, LazyReferenceMapper):
|
| 1236 |
+
return path in self.references.listdir()
|
| 1237 |
+
else:
|
| 1238 |
+
# this may be faster than building dircache for single calls, but
|
| 1239 |
+
# by looping will be slow for many calls; could cache it?
|
| 1240 |
+
return any(_.startswith(f"{path}/") for _ in self.references)
|
| 1241 |
+
|
| 1242 |
+
def isfile(self, path): # overwrite auto-sync version
|
| 1243 |
+
return path in self.references
|
| 1244 |
+
|
| 1245 |
+
async def _ls(self, path, detail=True, **kwargs): # calls fast sync code
|
| 1246 |
+
return self.ls(path, detail, **kwargs)
|
| 1247 |
+
|
| 1248 |
+
def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
|
| 1249 |
+
if withdirs:
|
| 1250 |
+
return super().find(
|
| 1251 |
+
path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs
|
| 1252 |
+
)
|
| 1253 |
+
if path:
|
| 1254 |
+
path = self._strip_protocol(path)
|
| 1255 |
+
r = sorted(k for k in self.references if k.startswith(path))
|
| 1256 |
+
else:
|
| 1257 |
+
r = sorted(self.references)
|
| 1258 |
+
if detail:
|
| 1259 |
+
if not self.dircache:
|
| 1260 |
+
self._dircache_from_items()
|
| 1261 |
+
return {k: self._ls_from_cache(k)[0] for k in r}
|
| 1262 |
+
else:
|
| 1263 |
+
return r
|
| 1264 |
+
|
| 1265 |
+
def info(self, path, **kwargs):
|
| 1266 |
+
out = self.references.get(path)
|
| 1267 |
+
if out is not None:
|
| 1268 |
+
if isinstance(out, (str, bytes)):
|
| 1269 |
+
return {"name": path, "type": "file", "size": len(_inline_data(out))}
|
| 1270 |
+
elif len(out) > 1:
|
| 1271 |
+
return {"name": path, "type": "file", "size": out[2]}
|
| 1272 |
+
else:
|
| 1273 |
+
out0 = [{"name": path, "type": "file", "size": None}]
|
| 1274 |
+
else:
|
| 1275 |
+
out = self.ls(path, True)
|
| 1276 |
+
out0 = [o for o in out if o["name"] == path]
|
| 1277 |
+
if not out0:
|
| 1278 |
+
return {"name": path, "type": "directory", "size": 0}
|
| 1279 |
+
if out0[0]["size"] is None:
|
| 1280 |
+
# if this is a whole remote file, update size using remote FS
|
| 1281 |
+
prot, _ = split_protocol(self.references[path][0])
|
| 1282 |
+
out0[0]["size"] = self.fss[prot].size(self.references[path][0])
|
| 1283 |
+
return out0[0]
|
| 1284 |
+
|
| 1285 |
+
async def _info(self, path, **kwargs):
|
| 1286 |
+
out = self.references.get(path)
|
| 1287 |
+
if isinstance(out, (list, tuple)) and len(out) == 1:
|
| 1288 |
+
# whole remote file: the size must come from the remote FS, which
|
| 1289 |
+
# cannot be called synchronously from inside the event loop
|
| 1290 |
+
prot, _ = split_protocol(out[0])
|
| 1291 |
+
fs = self.fss[prot]
|
| 1292 |
+
if fs.async_impl:
|
| 1293 |
+
size = await fs._size(out[0])
|
| 1294 |
+
else:
|
| 1295 |
+
size = fs.size(out[0])
|
| 1296 |
+
return {"name": path, "type": "file", "size": size}
|
| 1297 |
+
return self.info(path) # calls fast sync code
|
| 1298 |
+
|
| 1299 |
+
async def _rm_file(self, path, **kwargs):
|
| 1300 |
+
self.references.pop(
|
| 1301 |
+
path, None
|
| 1302 |
+
) # ignores FileNotFound, just as well for directories
|
| 1303 |
+
self.dircache.clear() # this is a bit heavy handed
|
| 1304 |
+
|
| 1305 |
+
async def _pipe_file(self, path, data, mode="overwrite", **kwargs):
|
| 1306 |
+
if mode == "create" and self.exists(path):
|
| 1307 |
+
raise FileExistsError
|
| 1308 |
+
# can be str or bytes
|
| 1309 |
+
self.references[path] = data
|
| 1310 |
+
self.dircache.clear() # this is a bit heavy handed
|
| 1311 |
+
|
| 1312 |
+
async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
|
| 1313 |
+
# puts binary
|
| 1314 |
+
if mode == "create" and self.exists(rpath):
|
| 1315 |
+
raise FileExistsError
|
| 1316 |
+
with open(lpath, "rb") as f:
|
| 1317 |
+
self.references[rpath] = f.read()
|
| 1318 |
+
self.dircache.clear() # this is a bit heavy handed
|
| 1319 |
+
|
| 1320 |
+
def save_json(self, url, **storage_options):
|
| 1321 |
+
"""Write modified references into new location"""
|
| 1322 |
+
out = {}
|
| 1323 |
+
for k, v in self.references.items():
|
| 1324 |
+
if isinstance(v, bytes):
|
| 1325 |
+
try:
|
| 1326 |
+
out[k] = v.decode("ascii")
|
| 1327 |
+
except UnicodeDecodeError:
|
| 1328 |
+
out[k] = (b"base64:" + base64.b64encode(v)).decode()
|
| 1329 |
+
else:
|
| 1330 |
+
out[k] = v
|
| 1331 |
+
with fsspec.open(url, "wb", **storage_options) as f:
|
| 1332 |
+
f.write(json.dumps({"version": 1, "refs": out}).encode())
|
| 1333 |
+
|
| 1334 |
+
|
| 1335 |
+
class ReferenceFile(AbstractBufferedFile):
|
| 1336 |
+
def __init__(
|
| 1337 |
+
self,
|
| 1338 |
+
fs,
|
| 1339 |
+
path,
|
| 1340 |
+
mode="rb",
|
| 1341 |
+
block_size="default",
|
| 1342 |
+
autocommit=True,
|
| 1343 |
+
cache_type="readahead",
|
| 1344 |
+
cache_options=None,
|
| 1345 |
+
size=None,
|
| 1346 |
+
**kwargs,
|
| 1347 |
+
):
|
| 1348 |
+
super().__init__(
|
| 1349 |
+
fs,
|
| 1350 |
+
path,
|
| 1351 |
+
mode=mode,
|
| 1352 |
+
block_size=block_size,
|
| 1353 |
+
autocommit=autocommit,
|
| 1354 |
+
size=size,
|
| 1355 |
+
cache_type=cache_type,
|
| 1356 |
+
cache_options=cache_options,
|
| 1357 |
+
**kwargs,
|
| 1358 |
+
)
|
| 1359 |
+
part_or_url, self.start, self.end = self.fs._cat_common(self.path)
|
| 1360 |
+
protocol, _ = split_protocol(part_or_url)
|
| 1361 |
+
self.src_fs = self.fs.fss[protocol]
|
| 1362 |
+
self.src_path = part_or_url
|
| 1363 |
+
self._f = None
|
| 1364 |
+
|
| 1365 |
+
@property
|
| 1366 |
+
def f(self):
|
| 1367 |
+
if self._f is None or self._f.closed:
|
| 1368 |
+
self._f = self.src_fs._open(
|
| 1369 |
+
self.src_path,
|
| 1370 |
+
mode=self.mode,
|
| 1371 |
+
block_size=self.blocksize,
|
| 1372 |
+
autocommit=self.autocommit,
|
| 1373 |
+
cache_type="none",
|
| 1374 |
+
**self.kwargs,
|
| 1375 |
+
)
|
| 1376 |
+
return self._f
|
| 1377 |
+
|
| 1378 |
+
def close(self):
|
| 1379 |
+
if self._f is not None:
|
| 1380 |
+
self._f.close()
|
| 1381 |
+
return super().close()
|
| 1382 |
+
|
| 1383 |
+
def _fetch_range(self, start, end):
|
| 1384 |
+
start = start + self.start
|
| 1385 |
+
end = min(end + self.start, self.end)
|
| 1386 |
+
self.f.seek(start)
|
| 1387 |
+
return self.f.read(end - start)
|