-
-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathbase.py
1652 lines (1330 loc) · 55 KB
/
base.py
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""PyFilesystem base class.
The filesystem base class is common to all filesystems. If you
familiarize yourself with this (rather straightforward) API, you
can work with any of the supported filesystems.
"""
from __future__ import absolute_import, print_function, unicode_literals
import abc
import hashlib
import itertools
import os
import shutil
import threading
import time
import typing
from contextlib import closing
from functools import partial, wraps
import warnings
import six
from . import copy, errors, fsencode, iotools, move, tools, walk, wildcard
from .glob import BoundGlobber
from .mode import validate_open_mode
from .path import abspath, join, normpath
from .time import datetime_to_epoch
from .walk import Walker
if typing.TYPE_CHECKING:
from datetime import datetime
from threading import RLock
from typing import (
Any,
BinaryIO,
Callable,
Collection,
Dict,
IO,
Iterable,
Iterator,
List,
Mapping,
Optional,
Text,
Tuple,
Type,
Union,
)
from types import TracebackType
from .enums import ResourceType
from .info import Info, RawInfo
from .subfs import SubFS
from .permissions import Permissions
from .walk import BoundWalker
_F = typing.TypeVar("_F", bound="FS")
_T = typing.TypeVar("_T", bound="FS")
_OpendirFactory = Callable[[_T, Text], SubFS[_T]]
__all__ = ["FS"]
def _new_name(method, old_name):
"""Return a method with a deprecation warning."""
# Looks suspiciously like a decorator, but isn't!
@wraps(method)
def _method(*args, **kwargs):
warnings.warn(
"method '{}' has been deprecated, please rename to '{}'".format(
old_name, method.__name__
),
DeprecationWarning,
)
return method(*args, **kwargs)
deprecated_msg = """
Note:
.. deprecated:: 2.2.0
Please use `~{}`
""".format(
method.__name__
)
if hasattr(_method, "__doc__"):
_method.__doc__ += deprecated_msg
return _method
@six.add_metaclass(abc.ABCMeta)
class FS(object):
"""Base class for FS objects.
"""
# This is the "standard" meta namespace.
_meta = {} # type: Dict[Text, Union[Text, int, bool, None]]
# most FS will use default walking algorithms
walker_class = Walker
# default to SubFS, used by opendir and should be returned by makedir(s)
subfs_class = None
def __init__(self):
# type: (...) -> None
"""Create a filesystem. See help(type(self)) for accurate signature.
"""
self._closed = False
self._lock = threading.RLock()
super(FS, self).__init__()
def __del__(self):
"""Auto-close the filesystem on exit."""
self.close()
def __enter__(self):
# type: (...) -> FS
"""Allow use of filesystem as a context manager.
"""
return self
def __exit__(
self,
exc_type, # type: Optional[Type[BaseException]]
exc_value, # type: Optional[BaseException]
traceback, # type: Optional[TracebackType]
):
# type: (...) -> None
"""Close filesystem on exit.
"""
self.close()
@property
def glob(self):
"""`~fs.glob.BoundGlobber`: a globber object..
"""
return BoundGlobber(self)
@property
def walk(self):
# type: (_F) -> BoundWalker[_F]
"""`~fs.walk.BoundWalker`: a walker bound to this filesystem.
"""
return self.walker_class.bind(self)
# ---------------------------------------------------------------- #
# Required methods #
# Filesystems must implement these methods. #
# ---------------------------------------------------------------- #
@abc.abstractmethod
def getinfo(self, path, namespaces=None):
# type: (Text, Optional[Collection[Text]]) -> Info
"""Get information about a resource on a filesystem.
Arguments:
path (str): A path to a resource on the filesystem.
namespaces (list, optional): Info namespaces to query
(defaults to *[basic]*).
Returns:
~fs.info.Info: resource information object.
For more information regarding resource information, see :ref:`info`.
"""
@abc.abstractmethod
def listdir(self, path):
# type: (Text) -> List[Text]
"""Get a list of the resource names in a directory.
This method will return a list of the resources in a directory.
A *resource* is a file, directory, or one of the other types
defined in `~fs.enums.ResourceType`.
Arguments:
path (str): A path to a directory on the filesystem
Returns:
list: list of names, relative to ``path``.
Raises:
fs.errors.DirectoryExpected: If ``path`` is not a directory.
fs.errors.ResourceNotFound: If ``path`` does not exist.
"""
@abc.abstractmethod
def makedir(
self,
path, # type: Text
permissions=None, # type: Optional[Permissions]
recreate=False, # type: bool
):
# type: (...) -> SubFS[FS]
"""Make a directory.
Arguments:
path (str): Path to directory from root.
permissions (~fs.permissions.Permissions, optional): a
`Permissions` instance, or `None` to use default.
recreate (bool): Set to `True` to avoid raising an error if
the directory already exists (defaults to `False`).
Returns:
~fs.subfs.SubFS: a filesystem whose root is the new directory.
Raises:
fs.errors.DirectoryExists: If the path already exists.
fs.errors.ResourceNotFound: If the path is not found.
"""
@abc.abstractmethod
def openbin(
self,
path, # type: Text
mode="r", # type: Text
buffering=-1, # type: int
**options # type: Any
):
# type: (...) -> BinaryIO
"""Open a binary file-like object.
Arguments:
path (str): A path on the filesystem.
mode (str): Mode to open file (must be a valid non-text mode,
defaults to *r*). Since this method only opens binary files,
the ``b`` in the mode string is implied.
buffering (int): Buffering policy (-1 to use default buffering,
0 to disable buffering, or any positive integer to indicate
a buffer size).
**options: keyword arguments for any additional information
required by the filesystem (if any).
Returns:
io.IOBase: a *file-like* object.
Raises:
fs.errors.FileExpected: If the path is not a file.
fs.errors.FileExists: If the file exists, and *exclusive mode*
is specified (``x`` in the mode).
fs.errors.ResourceNotFound: If the path does not exist.
"""
@abc.abstractmethod
def remove(self, path):
# type: (Text) -> None
"""Remove a file from the filesystem.
Arguments:
path (str): Path of the file to remove.
Raises:
fs.errors.FileExpected: If the path is a directory.
fs.errors.ResourceNotFound: If the path does not exist.
"""
@abc.abstractmethod
def removedir(self, path):
# type: (Text) -> None
"""Remove a directory from the filesystem.
Arguments:
path (str): Path of the directory to remove.
Raises:
fs.errors.DirectoryNotEmpty: If the directory is not empty (
see `~fs.base.FS.removetree` for a way to remove the
directory contents.).
fs.errors.DirectoryExpected: If the path does not refer to
a directory.
fs.errors.ResourceNotFound: If no resource exists at the
given path.
fs.errors.RemoveRootError: If an attempt is made to remove
the root directory (i.e. ``'/'``)
"""
@abc.abstractmethod
def setinfo(self, path, info):
# type: (Text, RawInfo) -> None
"""Set info on a resource.
This method is the complement to `~fs.base.FS.getinfo`
and is used to set info values on a resource.
Arguments:
path (str): Path to a resource on the filesystem.
info (dict): Dictionary of resource info.
Raises:
fs.errors.ResourceNotFound: If ``path`` does not exist
on the filesystem
The ``info`` dict should be in the same format as the raw
info returned by ``getinfo(file).raw``.
Example:
>>> details_info = {"details": {
... "modified": time.time()
... }}
>>> my_fs.setinfo('file.txt', details_info)
"""
# ---------------------------------------------------------------- #
# Optional methods #
# Filesystems *may* implement these methods. #
# ---------------------------------------------------------------- #
def appendbytes(self, path, data):
# type: (Text, bytes) -> None
# FIXME(@althonos): accept bytearray and memoryview as well ?
"""Append bytes to the end of a file, creating it if needed.
Arguments:
path (str): Path to a file.
data (bytes): Bytes to append.
Raises:
TypeError: If ``data`` is not a `bytes` instance.
fs.errors.ResourceNotFound: If a parent directory of
``path`` does not exist.
"""
if not isinstance(data, bytes):
raise TypeError("must be bytes")
with self._lock:
with self.open(path, "ab") as append_file:
append_file.write(data)
def appendtext(
self,
path, # type: Text
text, # type: Text
encoding="utf-8", # type: Text
errors=None, # type: Optional[Text]
newline="", # type: Text
):
# type: (...) -> None
"""Append text to the end of a file, creating it if needed.
Arguments:
path (str): Path to a file.
text (str): Text to append.
encoding (str): Encoding for text files (defaults to ``utf-8``).
errors (str, optional): What to do with unicode decode errors
(see `codecs` module for more information).
newline (str): Newline parameter.
Raises:
TypeError: if ``text`` is not an unicode string.
fs.errors.ResourceNotFound: if a parent directory of
``path`` does not exist.
"""
if not isinstance(text, six.text_type):
raise TypeError("must be unicode string")
with self._lock:
with self.open(
path, "at", encoding=encoding, errors=errors, newline=newline
) as append_file:
append_file.write(text)
def close(self):
# type: () -> None
"""Close the filesystem and release any resources.
It is important to call this method when you have finished
working with the filesystem. Some filesystems may not finalize
changes until they are closed (archives for example). You may
call this method explicitly (it is safe to call close multiple
times), or you can use the filesystem as a context manager to
automatically close.
Example:
>>> with OSFS('~/Desktop') as desktop_fs:
... desktop_fs.writetext(
... 'note.txt',
... "Don't forget to tape Game of Thrones"
... )
If you attempt to use a filesystem that has been closed, a
`~fs.errors.FilesystemClosed` exception will be thrown.
"""
self._closed = True
def copy(self, src_path, dst_path, overwrite=False):
# type: (Text, Text, bool) -> None
"""Copy file contents from ``src_path`` to ``dst_path``.
Arguments:
src_path (str): Path of source file.
dst_path (str): Path to destination file.
overwrite (bool): If `True`, overwrite the destination file
if it exists (defaults to `False`).
Raises:
fs.errors.DestinationExists: If ``dst_path`` exists,
and ``overwrite`` is `False`.
fs.errors.ResourceNotFound: If a parent directory of
``dst_path`` does not exist.
"""
with self._lock:
if not overwrite and self.exists(dst_path):
raise errors.DestinationExists(dst_path)
with closing(self.open(src_path, "rb")) as read_file:
# FIXME(@althonos): typing complains because open return IO
self.upload(dst_path, read_file) # type: ignore
def copydir(self, src_path, dst_path, create=False):
# type: (Text, Text, bool) -> None
"""Copy the contents of ``src_path`` to ``dst_path``.
Arguments:
src_path (str): Path of source directory.
dst_path (str): Path to destination directory.
create (bool): If `True`, then ``dst_path`` will be created
if it doesn't exist already (defaults to `False`).
Raises:
fs.errors.ResourceNotFound: If the ``dst_path``
does not exist, and ``create`` is not `True`.
"""
with self._lock:
if not create and not self.exists(dst_path):
raise errors.ResourceNotFound(dst_path)
if not self.getinfo(src_path).is_dir:
raise errors.DirectoryExpected(src_path)
copy.copy_dir(self, src_path, self, dst_path)
def create(self, path, wipe=False):
# type: (Text, bool) -> bool
"""Create an empty file.
The default behavior is to create a new file if one doesn't
already exist. If ``wipe`` is `True`, any existing file will
be truncated.
Arguments:
path (str): Path to a new file in the filesystem.
wipe (bool): If `True`, truncate any existing
file to 0 bytes (defaults to `False`).
Returns:
bool: `True` if a new file had to be created.
"""
with self._lock:
if not wipe and self.exists(path):
return False
with closing(self.open(path, "wb")):
pass
return True
def desc(self, path):
# type: (Text) -> Text
"""Return a short descriptive text regarding a path.
Arguments:
path (str): A path to a resource on the filesystem.
Returns:
str: a short description of the path.
"""
if not self.exists(path):
raise errors.ResourceNotFound(path)
try:
syspath = self.getsyspath(path)
except (errors.ResourceNotFound, errors.NoSysPath):
return "{} on {}".format(path, self)
else:
return syspath
def exists(self, path):
# type: (Text) -> bool
"""Check if a path maps to a resource.
Arguments:
path (str): Path to a resource.
Returns:
bool: `True` if a resource exists at the given path.
"""
try:
self.getinfo(path)
except errors.ResourceNotFound:
return False
else:
return True
def filterdir(
self,
path, # type: Text
files=None, # type: Optional[Iterable[Text]]
dirs=None, # type: Optional[Iterable[Text]]
exclude_dirs=None, # type: Optional[Iterable[Text]]
exclude_files=None, # type: Optional[Iterable[Text]]
namespaces=None, # type: Optional[Collection[Text]]
page=None, # type: Optional[Tuple[int, int]]
):
# type: (...) -> Iterator[Info]
"""Get an iterator of resource info, filtered by patterns.
This method enhances `~fs.base.FS.scandir` with additional
filtering functionality.
Arguments:
path (str): A path to a directory on the filesystem.
files (list, optional): A list of UNIX shell-style patterns
to filter file names, e.g. ``['*.py']``.
dirs (list, optional): A list of UNIX shell-style patterns
to filter directory names.
exclude_dirs (list, optional): A list of patterns used
to exclude directories.
exclude_files (list, optional): A list of patterns used
to exclude files.
namespaces (list, optional): A list of namespaces to include
in the resource information, e.g. ``['basic', 'access']``.
page (tuple, optional): May be a tuple of ``(<start>, <end>)``
indexes to return an iterator of a subset of the resource
info, or `None` to iterate over the entire directory.
Paging a directory scan may be necessary for very large
directories.
Returns:
~collections.abc.Iterator: an iterator of `Info` objects.
"""
resources = self.scandir(path, namespaces=namespaces)
filters = []
def match_dir(patterns, info):
# type: (Optional[Iterable[Text]], Info) -> bool
"""Pattern match info.name.
"""
return info.is_file or self.match(patterns, info.name)
def match_file(patterns, info):
# type: (Optional[Iterable[Text]], Info) -> bool
"""Pattern match info.name.
"""
return info.is_dir or self.match(patterns, info.name)
def exclude_dir(patterns, info):
# type: (Optional[Iterable[Text]], Info) -> bool
"""Pattern match info.name.
"""
return info.is_file or not self.match(patterns, info.name)
def exclude_file(patterns, info):
# type: (Optional[Iterable[Text]], Info) -> bool
"""Pattern match info.name.
"""
return info.is_dir or not self.match(patterns, info.name)
if files:
filters.append(partial(match_file, files))
if dirs:
filters.append(partial(match_dir, dirs))
if exclude_dirs:
filters.append(partial(exclude_dir, exclude_dirs))
if exclude_files:
filters.append(partial(exclude_file, exclude_files))
if filters:
resources = (
info for info in resources if all(_filter(info) for _filter in filters)
)
iter_info = iter(resources)
if page is not None:
start, end = page
iter_info = itertools.islice(iter_info, start, end)
return iter_info
def readbytes(self, path):
# type: (Text) -> bytes
"""Get the contents of a file as bytes.
Arguments:
path (str): A path to a readable file on the filesystem.
Returns:
bytes: the file contents.
Raises:
fs.errors.ResourceNotFound: if ``path`` does not exist.
"""
with closing(self.open(path, mode="rb")) as read_file:
contents = read_file.read()
return contents
getbytes = _new_name(readbytes, "getbytes")
def download(self, path, file, chunk_size=None, **options):
# type: (Text, BinaryIO, Optional[int], **Any) -> None
"""Copies a file from the filesystem to a file-like object.
This may be more efficient that opening and copying files
manually if the filesystem supplies an optimized method.
Arguments:
path (str): Path to a resource.
file (file-like): A file-like object open for writing in
binary mode.
chunk_size (int, optional): Number of bytes to read at a
time, if a simple copy is used, or `None` to use
sensible default.
**options: Implementation specific options required to open
the source file.
Note that the file object ``file`` will *not* be closed by this
method. Take care to close it after this method completes
(ideally with a context manager).
Example:
>>> with open('starwars.mov', 'wb') as write_file:
... my_fs.download('/movies/starwars.mov', write_file)
"""
with self._lock:
with self.openbin(path, **options) as read_file:
tools.copy_file_data(read_file, file, chunk_size=chunk_size)
getfile = _new_name(download, "getfile")
def readtext(
self,
path, # type: Text
encoding=None, # type: Optional[Text]
errors=None, # type: Optional[Text]
newline="", # type: Text
):
# type: (...) -> Text
"""Get the contents of a file as a string.
Arguments:
path (str): A path to a readable file on the filesystem.
encoding (str, optional): Encoding to use when reading contents
in text mode (defaults to `None`, reading in binary mode).
errors (str, optional): Unicode errors parameter.
newline (str): Newlines parameter.
Returns:
str: file contents.
Raises:
fs.errors.ResourceNotFound: If ``path`` does not exist.
"""
with closing(
self.open(
path, mode="rt", encoding=encoding, errors=errors, newline=newline
)
) as read_file:
contents = read_file.read()
return contents
gettext = _new_name(readtext, "gettext")
def getmeta(self, namespace="standard"):
# type: (Text) -> Mapping[Text, object]
"""Get meta information regarding a filesystem.
Arguments:
namespace (str): The meta namespace (defaults
to ``"standard"``).
Returns:
dict: the meta information.
Meta information is associated with a *namespace* which may be
specified with the ``namespace`` parameter. The default namespace,
``"standard"``, contains common information regarding the
filesystem's capabilities. Some filesystems may provide other
namespaces which expose less common or implementation specific
information. If a requested namespace is not supported by
a filesystem, then an empty dictionary will be returned.
The ``"standard"`` namespace supports the following keys:
=================== ============================================
key Description
------------------- --------------------------------------------
case_insensitive `True` if this filesystem is case
insensitive.
invalid_path_chars A string containing the characters that
may not be used on this filesystem.
max_path_length Maximum number of characters permitted in
a path, or `None` for no limit.
max_sys_path_length Maximum number of characters permitted in
a sys path, or `None` for no limit.
network `True` if this filesystem requires a
network.
read_only `True` if this filesystem is read only.
supports_rename `True` if this filesystem supports an
`os.rename` operation.
=================== ============================================
Most builtin filesystems will provide all these keys, and third-
party filesystems should do so whenever possible, but a key may
not be present if there is no way to know the value.
Note:
Meta information is constant for the lifetime of the
filesystem, and may be cached.
"""
if namespace == "standard":
meta = self._meta.copy()
else:
meta = {}
return meta
def getsize(self, path):
# type: (Text) -> int
"""Get the size (in bytes) of a resource.
Arguments:
path (str): A path to a resource.
Returns:
int: the *size* of the resource.
The *size* of a file is the total number of readable bytes,
which may not reflect the exact number of bytes of reserved
disk space (or other storage medium).
The size of a directory is the number of bytes of overhead
use to store the directory entry.
"""
size = self.getdetails(path).size
return size
def getsyspath(self, path):
# type: (Text) -> Text
"""Get the *system path* of a resource.
Parameters:
path (str): A path on the filesystem.
Returns:
str: the *system path* of the resource, if any.
Raises:
fs.errors.NoSysPath: If there is no corresponding system path.
A system path is one recognized by the OS, that may be used
outside of PyFilesystem (in an application or a shell for
example). This method will get the corresponding system path
that would be referenced by ``path``.
Not all filesystems have associated system paths. Network and
memory based filesystems, for example, may not physically store
data anywhere the OS knows about. It is also possible for some
paths to have a system path, whereas others don't.
This method will always return a str on Py3.* and unicode
on Py2.7. See `~getospath` if you need to encode the path as
bytes.
If ``path`` doesn't have a system path, a `~fs.errors.NoSysPath`
exception will be thrown.
Note:
A filesystem may return a system path even if no
resource is referenced by that path -- as long as it can
be certain what that system path would be.
"""
raise errors.NoSysPath(path=path)
def getospath(self, path):
# type: (Text) -> bytes
"""Get a *system path* to a resource, encoded in the operating
system's prefered encoding.
Parameters:
path (str): A path on the filesystem.
Returns:
str: the *system path* of the resource, if any.
Raises:
fs.errors.NoSysPath: If there is no corresponding system path.
This method takes the output of `~getsyspath` and encodes it to
the filesystem's prefered encoding. In Python3 this step is
not required, as the `os` module will do it automatically. In
Python2.7, the encoding step is required to support filenames
on the filesystem that don't encode correctly.
Note:
If you want your code to work in Python2.7 and Python3 then
use this method if you want to work will the OS filesystem
outside of the OSFS interface.
"""
syspath = self.getsyspath(path)
ospath = fsencode(syspath)
return ospath
def gettype(self, path):
# type: (Text) -> ResourceType
"""Get the type of a resource.
Parameters:
path (str): A path on the filesystem.
Returns:
~fs.enums.ResourceType: the type of the resource.
A type of a resource is an integer that identifies the what
the resource references. The standard type integers may be one
of the values in the `~fs.enums.ResourceType` enumerations.
The most common resource types, supported by virtually all
filesystems are ``directory`` (1) and ``file`` (2), but the
following types are also possible:
=================== ======
ResourceType value
------------------- ------
unknown 0
directory 1
file 2
character 3
block_special_file 4
fifo 5
socket 6
symlink 7
=================== ======
Standard resource types are positive integers, negative values
are reserved for implementation specific resource types.
"""
resource_type = self.getdetails(path).type
return resource_type
def geturl(self, path, purpose="download"):
# type: (Text, Text) -> Text
"""Get the URL to a given resource.
Parameters:
path (str): A path on the filesystem
purpose (str): A short string that indicates which URL
to retrieve for the given path (if there is more than
one). The default is ``'download'``, which should return
a URL that serves the file. Other filesystems may support
other values for ``purpose``.
Returns:
str: a URL.
Raises:
fs.errors.NoURL: If the path does not map to a URL.
"""
raise errors.NoURL(path, purpose)
def hassyspath(self, path):
# type: (Text) -> bool
"""Check if a path maps to a system path.
Parameters:
path (str): A path on the filesystem.
Returns:
bool: `True` if the resource at ``path`` has a *syspath*.
"""
has_sys_path = True
try:
self.getsyspath(path)
except errors.NoSysPath:
has_sys_path = False
return has_sys_path
def hasurl(self, path, purpose="download"):
# type: (Text, Text) -> bool
"""Check if a path has a corresponding URL.
Parameters:
path (str): A path on the filesystem.
purpose (str): A purpose parameter, as given in
`~fs.base.FS.geturl`.
Returns:
bool: `True` if an URL for the given purpose exists.
"""
has_url = True
try:
self.geturl(path, purpose=purpose)
except errors.NoURL:
has_url = False
return has_url
def isclosed(self):
# type: () -> bool
"""Check if the filesystem is closed.
"""
return getattr(self, "_closed", False)
def isdir(self, path):
# type: (Text) -> bool
"""Check if a path maps to an existing directory.
Parameters:
path (str): A path on the filesystem.
Returns:
bool: `True` if ``path`` maps to a directory.
"""
try:
return self.getinfo(path).is_dir
except errors.ResourceNotFound:
return False
def isempty(self, path):
# type: (Text) -> bool
"""Check if a directory is empty.
A directory is considered empty when it does not contain
any file or any directory.
Parameters:
path (str): A path to a directory on the filesystem.
Returns:
bool: `True` if the directory is empty.
Raises:
errors.DirectoryExpected: If ``path`` is not a directory.
errors.ResourceNotFound: If ``path`` does not exist.
"""
return next(iter(self.scandir(path)), None) is None
def isfile(self, path):
# type: (Text) -> bool
"""Check if a path maps to an existing file.
Parameters:
path (str): A path on the filesystem.
Returns:
bool: `True` if ``path`` maps to a file.
"""
try:
return not self.getinfo(path).is_dir
except errors.ResourceNotFound:
return False
def islink(self, path):
# type: (Text) -> bool
"""Check if a path maps to a symlink.
Parameters:
path (str): A path on the filesystem.
Returns:
bool: `True` if ``path`` maps to a symlink.
"""
self.getinfo(path)
return False
def lock(self):
# type: () -> RLock
"""Get a context manager that *locks* the filesystem.
Locking a filesystem gives a thread exclusive access to it.
Other threads will block until the threads with the lock has
left the context manager.
Returns:
threading.RLock: a lock specific to the filesystem instance.
Example:
>>> with my_fs.lock(): # May block