1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
|
"""Manage several filesystems through a single view.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from collections import OrderedDict, namedtuple
from operator import itemgetter
from . import errors
from .base import FS
from .mode import check_writable
from .opener import open_fs
from .path import abspath, normpath
if typing.TYPE_CHECKING:
from typing import (
IO,
Any,
BinaryIO,
Collection,
Iterator,
List,
MutableMapping,
MutableSet,
Optional,
Text,
Tuple,
)
from .enums import ResourceType
from .info import Info, RawInfo
from .permissions import Permissions
from .subfs import SubFS
M = typing.TypeVar("M", bound="MultiFS")
_PrioritizedFS = namedtuple("_PrioritizedFS", ["priority", "fs"])
class MultiFS(FS):
"""A filesystem that delegates to a sequence of other filesystems.
Operations on the MultiFS will try each 'child' filesystem in order,
until it succeeds. In effect, creating a filesystem that combines
the files and dirs of its children.
"""
_meta = {"virtual": True, "read_only": False, "case_insensitive": False}
def __init__(self, auto_close=True):
# type: (bool) -> None
"""Create a new MultiFS.
Arguments:
auto_close (bool): If `True` (the default), the child
filesystems will be closed when `MultiFS` is closed.
"""
super(MultiFS, self).__init__()
self._auto_close = auto_close
self.write_fs = None # type: Optional[FS]
self._write_fs_name = None # type: Optional[Text]
self._sort_index = 0
self._filesystems = {} # type: MutableMapping[Text, _PrioritizedFS]
self._fs_sequence = None # type: Optional[List[Tuple[Text, FS]]]
self._closed = False
def __repr__(self):
# type: () -> Text
if self._auto_close:
return "MultiFS()"
else:
return "MultiFS(auto_close=False)"
def __str__(self):
# type: () -> Text
return "<multifs>"
def add_fs(self, name, fs, write=False, priority=0):
# type: (Text, FS, bool, int) -> None
"""Add a filesystem to the MultiFS.
Arguments:
name (str): A unique name to refer to the filesystem being
added.
fs (FS or str): The filesystem (instance or URL) to add.
write (bool): If this value is True, then the ``fs`` will
be used as the writeable FS (defaults to False).
priority (int): An integer that denotes the priority of the
filesystem being added. Filesystems will be searched in
descending priority order and then by the reverse order
they were added. So by default, the most recently added
filesystem will be looked at first.
"""
if isinstance(fs, str):
fs = open_fs(fs)
if not isinstance(fs, FS):
raise TypeError("fs argument should be an FS object or FS URL")
self._filesystems[name] = _PrioritizedFS(
priority=(priority, self._sort_index), fs=fs
)
self._sort_index += 1
self._resort()
if write:
self.write_fs = fs
self._write_fs_name = name
def get_fs(self, name):
# type: (Text) -> FS
"""Get a filesystem from its name.
Arguments:
name (str): The name of a filesystem previously added.
Returns:
FS: the filesystem added as ``name`` previously.
Raises:
KeyError: If no filesystem with given ``name`` could be found.
"""
return self._filesystems[name].fs
def _resort(self):
# type: () -> None
"""Force `iterate_fs` to re-sort on next reference."""
self._fs_sequence = None
def iterate_fs(self):
# type: () -> Iterator[Tuple[Text, FS]]
"""Get iterator that returns (name, fs) in priority order."""
if self._fs_sequence is None:
self._fs_sequence = [
(name, fs)
for name, (_order, fs) in sorted(
self._filesystems.items(), key=itemgetter(1), reverse=True
)
]
return iter(self._fs_sequence)
def _delegate(self, path):
# type: (Text) -> Optional[FS]
"""Get a filesystem which has a given path."""
for _name, fs in self.iterate_fs():
if fs.exists(path):
return fs
return None
def _delegate_required(self, path):
# type: (Text) -> FS
"""Check that there is a filesystem with the given ``path``."""
fs = self._delegate(path)
if fs is None:
raise errors.ResourceNotFound(path)
return fs
def _writable_required(self, path):
# type: (Text) -> FS
"""Check that ``path`` is writeable."""
if self.write_fs is None:
raise errors.ResourceReadOnly(path)
return self.write_fs
def which(self, path, mode="r"):
# type: (Text, Text) -> Tuple[Optional[Text], Optional[FS]]
"""Get a tuple of (name, fs) that the given path would map to.
Arguments:
path (str): A path on the filesystem.
mode (str): An `io.open` mode.
"""
if check_writable(mode):
return self._write_fs_name, self.write_fs
for name, fs in self.iterate_fs():
if fs.exists(path):
return name, fs
return None, None
def close(self):
# type: () -> None
self._closed = True
if self._auto_close:
try:
for _order, fs in self._filesystems.values():
fs.close()
finally:
self._filesystems.clear()
self._resort()
def getinfo(self, path, namespaces=None):
# type: (Text, Optional[Collection[Text]]) -> Info
self.check()
namespaces = namespaces or ()
fs = self._delegate(path)
if fs is None:
raise errors.ResourceNotFound(path)
_path = abspath(normpath(path))
info = fs.getinfo(_path, namespaces=namespaces)
return info
def listdir(self, path):
# type: (Text) -> List[Text]
self.check()
directory = []
exists = False
for _name, _fs in self.iterate_fs():
try:
directory.extend(_fs.listdir(path))
except errors.ResourceNotFound:
pass
else:
exists = True
if not exists:
raise errors.ResourceNotFound(path)
directory = list(OrderedDict.fromkeys(directory))
return directory
def makedir(
self, # type: M
path, # type: Text
permissions=None, # type: Optional[Permissions]
recreate=False, # type: bool
):
# type: (...) -> SubFS[FS]
self.check()
write_fs = self._writable_required(path)
return write_fs.makedir(path, permissions=permissions, recreate=recreate)
def openbin(self, path, mode="r", buffering=-1, **options):
# type: (Text, Text, int, **Any) -> BinaryIO
self.check()
if check_writable(mode):
_fs = self._writable_required(path)
else:
_fs = self._delegate_required(path)
return _fs.openbin(path, mode=mode, buffering=buffering, **options)
def remove(self, path):
# type: (Text) -> None
self.check()
fs = self._delegate_required(path)
return fs.remove(path)
def removedir(self, path):
# type: (Text) -> None
self.check()
fs = self._delegate_required(path)
return fs.removedir(path)
def scandir(
self,
path, # type: Text
namespaces=None, # type: Optional[Collection[Text]]
page=None, # type: Optional[Tuple[int, int]]
):
# type: (...) -> Iterator[Info]
self.check()
seen = set() # type: MutableSet[Text]
exists = False
for _name, fs in self.iterate_fs():
try:
for info in fs.scandir(path, namespaces=namespaces, page=page):
if info.name not in seen:
yield info
seen.add(info.name)
exists = True
except errors.ResourceNotFound:
pass
if not exists:
raise errors.ResourceNotFound(path)
def readbytes(self, path):
# type: (Text) -> bytes
self.check()
fs = self._delegate(path)
if fs is None:
raise errors.ResourceNotFound(path)
return fs.readbytes(path)
def download(self, path, file, chunk_size=None, **options):
# type: (Text, BinaryIO, Optional[int], **Any) -> None
fs = self._delegate_required(path)
return fs.download(path, file, chunk_size=chunk_size, **options)
def readtext(self, path, encoding=None, errors=None, newline=""):
# type: (Text, Optional[Text], Optional[Text], Text) -> Text
self.check()
fs = self._delegate_required(path)
return fs.readtext(path, encoding=encoding, errors=errors, newline=newline)
def getsize(self, path):
# type: (Text) -> int
self.check()
fs = self._delegate_required(path)
return fs.getsize(path)
def getsyspath(self, path):
# type: (Text) -> Text
self.check()
fs = self._delegate_required(path)
return fs.getsyspath(path)
def gettype(self, path):
# type: (Text) -> ResourceType
self.check()
fs = self._delegate_required(path)
return fs.gettype(path)
def geturl(self, path, purpose="download"):
# type: (Text, Text) -> Text
self.check()
fs = self._delegate_required(path)
return fs.geturl(path, purpose=purpose)
def hassyspath(self, path):
# type: (Text) -> bool
self.check()
fs = self._delegate(path)
return fs is not None and fs.hassyspath(path)
def hasurl(self, path, purpose="download"):
# type: (Text, Text) -> bool
self.check()
fs = self._delegate(path)
return fs is not None and fs.hasurl(path, purpose=purpose)
def isdir(self, path):
# type: (Text) -> bool
self.check()
fs = self._delegate(path)
return fs is not None and fs.isdir(path)
def isfile(self, path):
# type: (Text) -> bool
self.check()
fs = self._delegate(path)
return fs is not None and fs.isfile(path)
def setinfo(self, path, info):
# type:(Text, RawInfo) -> None
self.check()
write_fs = self._writable_required(path)
return write_fs.setinfo(path, info)
def validatepath(self, path):
# type: (Text) -> Text
self.check()
if self.write_fs is not None:
self.write_fs.validatepath(path)
else:
super(MultiFS, self).validatepath(path)
path = abspath(normpath(path))
return path
def makedirs(
self,
path, # type: Text
permissions=None, # type: Optional[Permissions]
recreate=False, # type: bool
):
# type: (...) -> SubFS[FS]
self.check()
write_fs = self._writable_required(path)
return write_fs.makedirs(path, permissions=permissions, recreate=recreate)
def open(
self,
path, # type: Text
mode="r", # type: Text
buffering=-1, # type: int
encoding=None, # type: Optional[Text]
errors=None, # type: Optional[Text]
newline="", # type: Text
**kwargs # type: Any
):
# type: (...) -> IO
self.check()
if check_writable(mode):
_fs = self._writable_required(path)
else:
_fs = self._delegate_required(path)
return _fs.open(
path,
mode=mode,
buffering=buffering,
encoding=encoding,
errors=errors,
newline=newline,
**kwargs
)
def upload(self, path, file, chunk_size=None, **options):
# type: (Text, BinaryIO, Optional[int], **Any) -> None
self._writable_required(path).upload(
path, file, chunk_size=chunk_size, **options
)
def writebytes(self, path, contents):
# type: (Text, bytes) -> None
self._writable_required(path).writebytes(path, contents)
def writetext(
self,
path, # type: Text
contents, # type: Text
encoding="utf-8", # type: Text
errors=None, # type: Optional[Text]
newline="", # type: Text
):
# type: (...) -> None
write_fs = self._writable_required(path)
return write_fs.writetext(
path, contents, encoding=encoding, errors=errors, newline=newline
)
|