Skip to content

gfs

Generic filesystem API dispatching over local paths and URL schemes.

This module is the entry point of the filesystem layer: it routes open/copy/stat/list/remove and related operations to the FileSystem backend registered for the scheme of the path or URL (file, ftp, http, gs, s3), backed by the fs/ subpackage. It also provides TempFile for atomic writes, RegexMatcher to filter enumerations, and registration helpers to extend the supported schemes with additional backends.

Example
import os
import tempfile

from py_misc_utils import gfs

root = tempfile.mkdtemp()

# gfs dispatches over the backend registered for the URL scheme.
with gfs.open(os.path.join(root, 'a.txt'), mode='w') as fd:
  fd.write('local file')

gfs.copy(os.path.join(root, 'a.txt'), os.path.join(root, 'b.txt'))

print(gfs.exists(os.path.join(root, 'b.txt')))

TempFile

Temporary file which is removed unless replaced into a final path.

The temporary path is always a local one: non-local nsdir/nspath arguments are ignored. After open() the descriptor attributes are mirrored onto the TempFile itself, while close() removes the file and replace() atomically moves it to its final destination path.

Example
import os
import tempfile

from py_misc_utils import gfs

final = os.path.join(tempfile.gettempdir(), 'report.pdf')

with gfs.TempFile(nspath=final, mode='w+b') as fd:
  fd.write(b'payload')
  fd.replace(final)

print(os.path.isfile(final))

Attributes:

Name Type Description
fd

The file descriptor object of the file, mirrored after open().

Source code in py_misc_utils/gfs.py
 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
class TempFile:
  """Temporary file which is removed unless replaced into a final path.

  The temporary path is always a local one: non-local nsdir/nspath
  arguments are ignored. After open() the descriptor attributes are
  mirrored onto the TempFile itself, while close() removes the file
  and replace() atomically moves it to its final destination path.

  Example:
    import os
    import tempfile

    from py_misc_utils import gfs

    final = os.path.join(tempfile.gettempdir(), 'report.pdf')

    with gfs.TempFile(nspath=final, mode='w+b') as fd:
      fd.write(b'payload')
      fd.replace(final)

    print(os.path.isfile(final))

  Attributes:
    fd: The file descriptor object of the file, mirrored after open().
  """

  def __init__(self, nsdir=None, nspath=None, **kwargs):
    """Create the path of the temporary file.

    Args:
      nsdir: Optional namespace directory the temp path is created in;
        non-local paths are ignored.
      nspath: Optional namespace path used to derive the temp path;
        non-local paths are ignored.
      **kwargs: Open keyword arguments used when open() is called.

    Attributes:
      fd: The file descriptor object of the file, mirrored after open().
    """
    nsdir = nsdir if nsdir is None or is_local_path(nsdir) else None
    nspath = nspath if nspath is None or is_local_path(nspath) else None

    self._fs, self._path = resolve_fs(fsu.temp_path(nspath=nspath, nsdir=nsdir),
                                      **kwargs)
    self._kwargs = kwargs
    self._fd, self._delete = None, False

  def open(self):
    """Open the file, mirroring its descriptor attributes.

    Returns:
      The TempFile instance itself.
    """
    self._fd = self._fs.open(self._path, **self._kwargs)
    self._delete = True
    mrf.mirror_all(self._fd, self, name='fd')

    return self

  def _close_fd(self):
    """Close the file descriptor, unmirroring its attributes."""
    if self._fd is not None:
      self._fd.close()
      mrf.unmirror(self, name='fd')
      self._fd = None

  def close(self):
    """Close the file and remove it, unless it was replaced."""
    self._close_fd()
    if self._delete:
      self._fs.remove(self._path)
      self._delete = False

  def replace(self, path):
    """Atomically move the file into its final destination path.

    Args:
      path: Destination path or URL.
    """
    self._close_fd()
    replace(self._path, path, src_fs=self._fs)
    self._delete = False

  def __enter__(self):
    """Open the file and return the TempFile itself."""
    self.open()

    return self

  def __exit__(self, *exc):
    """Close the file.

    Args:
      *exc: Exception information of the context, if any.

    Returns:
      False, so that exceptions are not suppressed.
    """
    self.close()

    return False

open()

Open the file, mirroring its descriptor attributes.

Returns:

Type Description

The TempFile instance itself.

Source code in py_misc_utils/gfs.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def open(self):
  """Open the file, mirroring its descriptor attributes.

  Returns:
    The TempFile instance itself.
  """
  self._fd = self._fs.open(self._path, **self._kwargs)
  self._delete = True
  mrf.mirror_all(self._fd, self, name='fd')

  return self

close()

Close the file and remove it, unless it was replaced.

Source code in py_misc_utils/gfs.py
110
111
112
113
114
115
def close(self):
  """Close the file and remove it, unless it was replaced."""
  self._close_fd()
  if self._delete:
    self._fs.remove(self._path)
    self._delete = False

replace(path)

Atomically move the file into its final destination path.

Parameters:

Name Type Description Default
path

Destination path or URL.

required
Source code in py_misc_utils/gfs.py
117
118
119
120
121
122
123
124
125
def replace(self, path):
  """Atomically move the file into its final destination path.

  Args:
    path: Destination path or URL.
  """
  self._close_fd()
  replace(self._path, path, src_fs=self._fs)
  self._delete = False

RegexMatcher

File name matcher enumerating the entries matching a regex.

Example
from py_misc_utils import gfs

matcher = gfs.RegexMatcher(r'.*\.txt$')
Source code in py_misc_utils/gfs.py
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
class RegexMatcher:
  """File name matcher enumerating the entries matching a regex.

  Example:
    from py_misc_utils import gfs

    matcher = gfs.RegexMatcher(r'.*\\.txt$')
  """

  def __init__(self, rex):
    """Compile the regular expression used to filter the file names.

    Matching is anchored at the start of the name, as done by
    re.match().

    Args:
      rex: Regular expression the file names must match.
    """
    self._rex = re.compile(rex)
    self.match = None

  def __call__(self, value):
    """Match a file name, recording the match object.

    The last match object is kept in the match attribute, so that the
    matched text is available to the caller after the call.

    Args:
      value: File name to match against the regular expression.

    Returns:
      True when the name matches.
    """
    self.match = re.match(self._rex, value)

    return self.match is not None

std_open(path, **kwargs)

Open a standard stream by name or a plain local file.

Example
import os
import tempfile

from py_misc_utils import gfs

root = tempfile.mkdtemp()

with gfs.std_open(os.path.join(root, 'a.txt'), mode='w') as fd:
  fd.write('plain local file')

with gfs.std_open('STDOUT') as fd:
  fd.write('stdout')

Parameters:

Name Type Description Default
path

Path of the file to open, or one of 'STDIN', 'STDOUT' or 'STDERR' to access the corresponding standard stream.

required
**kwargs

Open keyword arguments, ignored for the standard streams.

{}

Returns:

Type Description

A context manager yielding the opened file or standard stream.

Source code in py_misc_utils/gfs.py
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
def std_open(path, **kwargs):
  """Open a standard stream by name or a plain local file.

  Example:
    import os
    import tempfile

    from py_misc_utils import gfs

    root = tempfile.mkdtemp()

    with gfs.std_open(os.path.join(root, 'a.txt'), mode='w') as fd:
      fd.write('plain local file')

    with gfs.std_open('STDOUT') as fd:
      fd.write('stdout')

  Args:
    path: Path of the file to open, or one of 'STDIN', 'STDOUT' or
      'STDERR' to access the corresponding standard stream.
    **kwargs: Open keyword arguments, ignored for the standard streams.

  Returns:
    A context manager yielding the opened file or standard stream.
  """
  if isinstance(path, str) and (sfd := _STD_FILES.get(path)) is not None:
    return contextlib.nullcontext(sfd)

  return open(path, **kwargs)

open(source, **kwargs)

Open a path or URL through its FileSystem backend.

Parameters:

Name Type Description Default
source

Path or URL to open, or an already opened file-like object, which is yielded unchanged.

required
**kwargs

Open keyword arguments, including the cache settings.

{}

Returns:

Type Description

The opened file-like object, or a context manager yielding it.

Source code in py_misc_utils/gfs.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def open(source, **kwargs):
  """Open a path or URL through its FileSystem backend.

  Args:
    source: Path or URL to open, or an already opened file-like object,
      which is yielded unchanged.
    **kwargs: Open keyword arguments, including the cache settings.

  Returns:
    The opened file-like object, or a context manager yielding it.
  """
  if (path := path_of(source)) is not None:
    fs, fpath = resolve_fs(path, **kwargs)

    return fs.open(fpath, **kwargs)

  return contextlib.nullcontext(source)

open_local(path, **kwargs)

Open a plain local file, bypassing the URL dispatching.

Parameters:

Name Type Description Default
path

Path of the local file to open.

required
**kwargs

Open keyword arguments.

{}

Returns:

Type Description

The opened file-like object.

Source code in py_misc_utils/gfs.py
204
205
206
207
208
209
210
211
212
213
214
def open_local(path, **kwargs):
  """Open a plain local file, bypassing the URL dispatching.

  Args:
    path: Path of the local file to open.
    **kwargs: Open keyword arguments.

  Returns:
    The opened file-like object.
  """
  return open(path, **kwargs)

maybe_open(path, **kwargs)

Open a path, returning None instead of raising.

Parameters:

Name Type Description Default
path

Path or URL to open.

required
**kwargs

Open keyword arguments.

{}

Returns:

Type Description

The opened file-like object, or None when opening failed.

Source code in py_misc_utils/gfs.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def maybe_open(path, **kwargs):
  """Open a path, returning None instead of raising.

  Args:
    path: Path or URL to open.
    **kwargs: Open keyword arguments.

  Returns:
    The opened file-like object, or None when opening failed.
  """
  try:
    return open(path, **kwargs)
  # Open dispatches over all fs backends - each raises its own error types:
  # any open failure answers None, per the documented contract.
  except Exception:  # noqa: BLE001, S110
    pass

as_local(path, **kwargs)

Return a local path holding the contents of a path or URL.

Parameters:

Name Type Description Default
path

Path or URL to make available locally.

required
**kwargs

Keyword arguments forwarded to the backend, including the cache settings.

{}

Returns:

Type Description

The local path of the file, downloaded through the cache interface

when the contents are remote.

Source code in py_misc_utils/gfs.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def as_local(path, **kwargs):
  """Return a local path holding the contents of a path or URL.

  Args:
    path: Path or URL to make available locally.
    **kwargs: Keyword arguments forwarded to the backend, including the
      cache settings.

  Returns:
    The local path of the file, downloaded through the cache interface
    when the contents are remote.
  """
  fs, fpath = resolve_fs(path, **kwargs)

  return fs.as_local(fpath, **kwargs)

path_of(path)

Return the filesystem path of a path-like object.

Parameters:

Name Type Description Default
path

A string, a path-like object, or anything else.

required

Returns:

Type Description

The string path, or None when path is not path-like.

Source code in py_misc_utils/gfs.py
252
253
254
255
256
257
258
259
260
261
def path_of(path):
  """Return the filesystem path of a path-like object.

  Args:
    path: A string, a path-like object, or anything else.

  Returns:
    The string path, or None when path is not path-like.
  """
  return os.fspath(path) if isinstance(path, (str, os.PathLike)) else None

splitext(path)

Split a path or URL into its base and extension.

Parameters:

Name Type Description Default
path

Path or URL to split.

required

Returns:

Type Description

A PathSplit namedtuple with the path without the extension, the

extension without the leading dot, and the parsed URL.

Source code in py_misc_utils/gfs.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
def splitext(path):
  """Split a path or URL into its base and extension.

  Args:
    path: Path or URL to split.

  Returns:
    A PathSplit namedtuple with the path without the extension, the
    extension without the leading dot, and the parsed URL.
  """
  purl = uparse.urlparse(path)
  base, ext = os.path.splitext(purl.path)

  return PathSplit(base=base, ext=ext[1:], purl=purl)

is_file(path)

Check if a path exists and is a regular file.

Parameters:

Name Type Description Default
path

Path or URL to check.

required

Returns:

Type Description

True if the path is a regular file.

Source code in py_misc_utils/gfs.py
283
284
285
286
287
288
289
290
291
292
293
294
def is_file(path):
  """Check if a path exists and is a regular file.

  Args:
    path: Path or URL to check.

  Returns:
    True if the path is a regular file.
  """
  fs, fpath = resolve_fs(path)

  return fs.isfile(fpath)

is_dir(path)

Check if a path exists and is a directory.

Parameters:

Name Type Description Default
path

Path or URL to check.

required

Returns:

Type Description

True if the path is a directory.

Source code in py_misc_utils/gfs.py
297
298
299
300
301
302
303
304
305
306
307
308
def is_dir(path):
  """Check if a path exists and is a directory.

  Args:
    path: Path or URL to check.

  Returns:
    True if the path is a directory.
  """
  fs, fpath = resolve_fs(path)

  return fs.isdir(fpath)

exists(path)

Check if a path or URL exists.

Parameters:

Name Type Description Default
path

Path or URL to check.

required

Returns:

Type Description

True if the path exists.

Source code in py_misc_utils/gfs.py
311
312
313
314
315
316
317
318
319
320
321
322
def exists(path):
  """Check if a path or URL exists.

  Args:
    path: Path or URL to check.

  Returns:
    True if the path exists.
  """
  fs, fpath = resolve_fs(path)

  return fs.exists(fpath)

is_same_fs(*args)

Check if DirEntry objects belong to the same filesystem.

Parameters:

Name Type Description Default
*args

DirEntry objects to compare, each holding a path attribute.

()

Returns:

Type Description

True when every entry belongs to the same protocol and host.

Source code in py_misc_utils/gfs.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def is_same_fs(*args):
  """Check if DirEntry objects belong to the same filesystem.

  Args:
    *args: DirEntry objects to compare, each holding a path attribute.

  Returns:
    True when every entry belongs to the same protocol and host.
  """
  specs = []
  for fspath in args:
    purl = uparse.urlparse(fspath.path)
    if purl.scheme:
      specs.append((purl.scheme, purl.netloc))
    else:
      specs.append((_DEFAULT_LOCAL_PROTO, fsu.localfs_mount(purl.path)))

  return all(specs[0] == s for s in specs[1:])

is_local_proto(proto)

Check if a protocol refers to the local filesystem.

Parameters:

Name Type Description Default
proto

Protocol name to check.

required

Returns:

Type Description

True when the protocol is the default local one ('file').

Source code in py_misc_utils/gfs.py
348
349
350
351
352
353
354
355
356
357
def is_local_proto(proto):
  """Check if a protocol refers to the local filesystem.

  Args:
    proto: Protocol name to check.

  Returns:
    True when the protocol is the default local one ('file').
  """
  return proto == _DEFAULT_LOCAL_PROTO

is_local_fs(fs)

Check if a FileSystem backend operates on local paths.

Parameters:

Name Type Description Default
fs

FileSystem backend to check.

required

Returns:

Type Description

True when the backend id is the local protocol.

Source code in py_misc_utils/gfs.py
360
361
362
363
364
365
366
367
368
369
def is_local_fs(fs):
  """Check if a FileSystem backend operates on local paths.

  Args:
    fs: FileSystem backend to check.

  Returns:
    True when the backend id is the local protocol.
  """
  return is_local_proto(fs.ID)

is_local_path(path)

Check if a path or URL refers to the local filesystem.

Parameters:

Name Type Description Default
path

Path or URL to check.

required

Returns:

Type Description

True when the protocol of the path is the local one.

Source code in py_misc_utils/gfs.py
372
373
374
375
376
377
378
379
380
381
def is_local_path(path):
  """Check if a path or URL refers to the local filesystem.

  Args:
    path: Path or URL to check.

  Returns:
    True when the protocol of the path is the local one.
  """
  return is_local_proto(get_proto(path))

is_path(path)

Check if a string holds a path or URL.

Parameters:

Name Type Description Default
path

String to check.

required

Returns:

Type Description

True when the string contains a protocol, or starts with '/', './'

or '../'.

Source code in py_misc_utils/gfs.py
384
385
386
387
388
389
390
391
392
393
394
395
def is_path(path):
  """Check if a string holds a path or URL.

  Args:
    path: String to check.

  Returns:
    True when the string contains a protocol, or starts with '/', './'
    or '../'.
  """
  # It is a path is it contains a proto, or starts with '/', './' or '../'.
  return has_proto(path) or re.match(r'/|\.\.?/', path) is not None

has_proto(path)

Check if a string holds a protocol-qualified URL.

Parameters:

Name Type Description Default
path

String to check.

required

Returns:

Type Description

True when the string starts with a 'proto://' prefix.

Source code in py_misc_utils/gfs.py
398
399
400
401
402
403
404
405
406
407
def has_proto(path):
  """Check if a string holds a protocol-qualified URL.

  Args:
    path: String to check.

  Returns:
    True when the string starts with a 'proto://' prefix.
  """
  return re.match(r'\w+://', path) is not None

get_proto(path)

Return the protocol of a path or URL.

Parameters:

Name Type Description Default
path

Path or URL to inspect.

required

Returns:

Type Description

The lower-case protocol name, or the default local protocol for

plain paths.

Source code in py_misc_utils/gfs.py
410
411
412
413
414
415
416
417
418
419
420
421
422
def get_proto(path):
  """Return the protocol of a path or URL.

  Args:
    path: Path or URL to inspect.

  Returns:
    The lower-case protocol name, or the default local protocol for
    plain paths.
  """
  m = re.match(r'(\w+)://', path)

  return m.group(1).lower() if m else _DEFAULT_LOCAL_PROTO

resolve_paths(*paths)

Resolve multiple paths into FsPath entries.

Parameters:

Name Type Description Default
*paths

Paths or URLs to resolve; a (fs, path) tuple is used as-is when its filesystem is already given.

()

Returns:

Type Description

A tuple of FsPath namedtuple with the resolved backend and path.

Source code in py_misc_utils/gfs.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def resolve_paths(*paths):
  """Resolve multiple paths into FsPath entries.

  Args:
    *paths: Paths or URLs to resolve; a (fs, path) tuple is used as-is
      when its filesystem is already given.

  Returns:
    A tuple of FsPath namedtuple with the resolved backend and path.
  """
  resolved = []
  for path_arg in paths:
    if isinstance(path_arg, (list, tuple)):
      fs, path = path_arg
    else:
      fs, path = None, path_arg
    if fs is None:
      fs, path = resolve_fs(path)

    resolved.append(FsPath(fs, path))

  return tuple(resolved)

copy(src_path, dest_path, src_fs=None, dest_fs=None)

Copy a file across filesystems.

Example
import os
import tempfile

from py_misc_utils import gfs

root = tempfile.mkdtemp()
src = os.path.join(root, 'src.txt')

with open(src, 'w') as fd:
  fd.write('data')

gfs.copy(src, os.path.join(root, 'dst.txt'))

print(gfs.exists(os.path.join(root, 'dst.txt')))

Parameters:

Name Type Description Default
src_path

Source path or URL.

required
dest_path

Destination path or URL.

required
src_fs

Optional pre-resolved FileSystem of the source.

None
dest_fs

Optional pre-resolved FileSystem of the destination.

None
Source code in py_misc_utils/gfs.py
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
def copy(src_path, dest_path, src_fs=None, dest_fs=None):
  """Copy a file across filesystems.

  Example:
    import os
    import tempfile

    from py_misc_utils import gfs

    root = tempfile.mkdtemp()
    src = os.path.join(root, 'src.txt')

    with open(src, 'w') as fd:
      fd.write('data')

    gfs.copy(src, os.path.join(root, 'dst.txt'))

    print(gfs.exists(os.path.join(root, 'dst.txt')))

  Args:
    src_path: Source path or URL.
    dest_path: Destination path or URL.
    src_fs: Optional pre-resolved FileSystem of the source.
    dest_fs: Optional pre-resolved FileSystem of the destination.
  """
  src, dest = resolve_paths((src_fs, src_path), (dest_fs, dest_path))

  src.fs.copyfile(src.path, dest.fs, dest.path)

replace(src_path, dest_path, src_fs=None, dest_fs=None)

Replace a file with another one, across filesystems.

The rename is done in place when source and destination are on the same filesystem, otherwise it is implemented as a copy followed by a source removal.

Example
import os
import tempfile

from py_misc_utils import gfs

root = tempfile.mkdtemp()
src = os.path.join(root, 'src.txt')

with open(src, 'w') as fd:
  fd.write('data')

gfs.replace(src, os.path.join(root, 'moved.txt'))

print(gfs.exists(src), gfs.exists(os.path.join(root, 'moved.txt')))

Parameters:

Name Type Description Default
src_path

Source path or URL.

required
dest_path

Destination path or URL.

required
src_fs

Optional pre-resolved FileSystem of the source.

None
dest_fs

Optional pre-resolved FileSystem of the destination.

None
Source code in py_misc_utils/gfs.py
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
def replace(src_path, dest_path, src_fs=None, dest_fs=None):
  """Replace a file with another one, across filesystems.

  The rename is done in place when source and destination are on the
  same filesystem, otherwise it is implemented as a copy followed by a
  source removal.

  Example:
    import os
    import tempfile

    from py_misc_utils import gfs

    root = tempfile.mkdtemp()
    src = os.path.join(root, 'src.txt')

    with open(src, 'w') as fd:
      fd.write('data')

    gfs.replace(src, os.path.join(root, 'moved.txt'))

    print(gfs.exists(src), gfs.exists(os.path.join(root, 'moved.txt')))

  Args:
    src_path: Source path or URL.
    dest_path: Destination path or URL.
    src_fs: Optional pre-resolved FileSystem of the source.
    dest_fs: Optional pre-resolved FileSystem of the destination.
  """
  src, dest = resolve_paths((src_fs, src_path), (dest_fs, dest_path))

  if is_same_fs(src, dest):
    dest.fs.replace(src.path, dest.path)
  else:
    copy(src.path, dest.path, src_fs=src.fs, dest_fs=dest.fs)
    src.fs.remove(src.path)

remove(path)

Remove a file.

Parameters:

Name Type Description Default
path

Path or URL of the file to remove.

required
Source code in py_misc_utils/gfs.py
521
522
523
524
525
526
527
528
def remove(path):
  """Remove a file.

  Args:
    path: Path or URL of the file to remove.
  """
  fs, fpath = resolve_fs(path)
  fs.remove(fpath)

mkdir(path, **kwargs)

Create a directory.

Parameters:

Name Type Description Default
path

Path or URL of the directory to create.

required
**kwargs

Keyword arguments forwarded to the backend.

{}
Source code in py_misc_utils/gfs.py
531
532
533
534
535
536
537
538
539
def mkdir(path, **kwargs):
  """Create a directory.

  Args:
    path: Path or URL of the directory to create.
    **kwargs: Keyword arguments forwarded to the backend.
  """
  fs, fpath = resolve_fs(path)
  fs.mkdir(fpath, **kwargs)

makedirs(path, **kwargs)

Create a directory and all its parents.

Parameters:

Name Type Description Default
path

Path or URL of the directory to create.

required
**kwargs

Keyword arguments forwarded to the backend.

{}
Source code in py_misc_utils/gfs.py
542
543
544
545
546
547
548
549
550
def makedirs(path, **kwargs):
  """Create a directory and all its parents.

  Args:
    path: Path or URL of the directory to create.
    **kwargs: Keyword arguments forwarded to the backend.
  """
  fs, fpath = resolve_fs(path)
  fs.makedirs(fpath, **kwargs)

rmdir(path)

Remove an empty directory.

Parameters:

Name Type Description Default
path

Path or URL of the directory to remove.

required
Source code in py_misc_utils/gfs.py
553
554
555
556
557
558
559
560
def rmdir(path):
  """Remove an empty directory.

  Args:
    path: Path or URL of the directory to remove.
  """
  fs, fpath = resolve_fs(path)
  fs.rmdir(fpath)

rmtree(path, **kwargs)

Recursively remove a directory tree.

Parameters:

Name Type Description Default
path

Path or URL of the directory tree to remove.

required
**kwargs

Keyword arguments forwarded to the backend.

{}
Source code in py_misc_utils/gfs.py
563
564
565
566
567
568
569
570
571
def rmtree(path, **kwargs):
  """Recursively remove a directory tree.

  Args:
    path: Path or URL of the directory tree to remove.
    **kwargs: Keyword arguments forwarded to the backend.
  """
  fs, fpath = resolve_fs(path)
  fs.rmtree(fpath, **kwargs)

stat(path)

Stat a path or URL.

Parameters:

Name Type Description Default
path

Path or URL to stat.

required

Returns:

Type Description

The DirEntry of the path.

Source code in py_misc_utils/gfs.py
574
575
576
577
578
579
580
581
582
583
584
585
def stat(path):
  """Stat a path or URL.

  Args:
    path: Path or URL to stat.

  Returns:
    The DirEntry of the path.
  """
  fs, fpath = resolve_fs(path)

  return fs.stat(fpath)

link(src_path, dest_path)

Create a hard link within the same filesystem.

Parameters:

Name Type Description Default
src_path

Path or URL of the existing file.

required
dest_path

Path or URL of the link to create.

required
Source code in py_misc_utils/gfs.py
588
589
590
591
592
593
594
595
596
597
598
599
600
def link(src_path, dest_path):
  """Create a hard link within the same filesystem.

  Args:
    src_path: Path or URL of the existing file.
    dest_path: Path or URL of the link to create.
  """
  src, dest = resolve_paths(src_path, dest_path)

  tas.check(is_same_fs(src, dest),
            msg=f'Unable to link across file systems: {src_path} -> {dest_path}')

  src.fs.link(src.path, dest.path)

symlink(src_path, dest_path)

Create a symbolic link within the same filesystem.

Parameters:

Name Type Description Default
src_path

Path or URL of the existing file.

required
dest_path

Path or URL of the link to create.

required
Source code in py_misc_utils/gfs.py
603
604
605
606
607
608
609
610
611
612
613
614
615
def symlink(src_path, dest_path):
  """Create a symbolic link within the same filesystem.

  Args:
    src_path: Path or URL of the existing file.
    dest_path: Path or URL of the link to create.
  """
  src, dest = resolve_paths(src_path, dest_path)

  tas.check(is_same_fs(src, dest),
            msg=f'Unable to symlink across file systems: {src_path} -> {dest_path}')

  src.fs.symlink(src.path, dest.path)

enumerate_files(path, matcher=None, return_stats=False)

Enumerate the file names of a directory.

Example
import os
import tempfile

from py_misc_utils import gfs

root = tempfile.mkdtemp()

gfs.makedirs(os.path.join(root, 'sub'))
for name in ('a.txt', 'b.log'):
  with open(os.path.join(root, name), 'w') as fd:
    fd.write(name)

names = list(gfs.enumerate_files(root, matcher=gfs.RegexMatcher(r'.*\.txt$')))

Parameters:

Name Type Description Default
path

Path or URL of the directory to enumerate.

required
matcher

Optional matcher object filtering the yielded names.

None
return_stats

If True, yield (name, DirEntry) pairs instead of plain names (default: False).

False

Yields:

Type Description

The file names of the directory, or (name, DirEntry) pairs when

return_stats is set.

Source code in py_misc_utils/gfs.py
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
def enumerate_files(path, matcher=None, return_stats=False):
  """Enumerate the file names of a directory.

  Example:
    import os
    import tempfile

    from py_misc_utils import gfs

    root = tempfile.mkdtemp()

    gfs.makedirs(os.path.join(root, 'sub'))
    for name in ('a.txt', 'b.log'):
      with open(os.path.join(root, name), 'w') as fd:
        fd.write(name)

    names = list(gfs.enumerate_files(root, matcher=gfs.RegexMatcher(r'.*\\.txt$')))

  Args:
    path: Path or URL of the directory to enumerate.
    matcher: Optional matcher object filtering the yielded names.
    return_stats: If True, yield (name, DirEntry) pairs instead of
      plain names (default: False).

  Yields:
    The file names of the directory, or (name, DirEntry) pairs when
    return_stats is set.
  """
  fs, fpath = resolve_fs(path)

  for de in fs.list(fpath):
    if matcher is None or matcher(de.name):
      if return_stats:
        yield de.name, de
      else:
        yield de.name

normpath(path)

Return the backend-specific path of a path or URL.

This is the path as seen by the FileSystem backend of the URL scheme: the URL itself for local paths, the full URL for remote ones (each backend parses it again to extract the server credentials and the remote path).

Parameters:

Name Type Description Default
path

Path or URL to normalize.

required

Returns:

Type Description

The normalized backend-specific path.

Source code in py_misc_utils/gfs.py
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
def normpath(path):
  """Return the backend-specific path of a path or URL.

  This is the path as seen by the FileSystem backend of the URL
  scheme: the URL itself for local paths, the full URL for remote
  ones (each backend parses it again to extract the server
  credentials and the remote path).

  Args:
    path: Path or URL to normalize.

  Returns:
    The normalized backend-specific path.
  """
  _, fpath = resolve_fs(path)

  return fpath

cache_dir()

Return the current directory used to cache remote file contents.

Source code in py_misc_utils/gfs.py
716
717
718
def cache_dir():
  """Return the current directory used to cache remote file contents."""
  return _CACHE_DIR

set_cache_dir(path)

Set the directory used to cache remote file contents.

Parameters:

Name Type Description Default
path

Path of the cache directory.

required
Source code in py_misc_utils/gfs.py
721
722
723
724
725
726
727
728
729
def set_cache_dir(path):
  """Set the directory used to cache remote file contents.

  Args:
    path: Path of the cache directory.
  """
  global _CACHE_DIR

  _CACHE_DIR = fsu.normpath(path)

find_mount(path)

Find the mount point of a local path.

Parameters:

Name Type Description Default
path

Path or URL to inspect.

required

Returns:

Type Description

The mount point of the path for local filesystems, or None for

remote ones.

Source code in py_misc_utils/gfs.py
732
733
734
735
736
737
738
739
740
741
742
743
744
def find_mount(path):
  """Find the mount point of a local path.

  Args:
    path: Path or URL to inspect.

  Returns:
    The mount point of the path for local filesystems, or None for
    remote ones.
  """
  fs, fpath = resolve_fs(path)

  return fsu.localfs_mount(fpath) if is_local_fs(fs) else None

register_fs(cls)

Register a FileSystem backend class for its protocols.

Parameters:

Name Type Description Default
cls

The FileSystem class, exposing IDS and a cache_iface/cache_dir accepting constructor.

required
Source code in py_misc_utils/gfs.py
750
751
752
753
754
755
756
757
758
759
def register_fs(cls):
  """Register a FileSystem backend class for its protocols.

  Args:
    cls: The FileSystem class, exposing IDS and a cache_iface/cache_dir
      accepting constructor.
  """
  for fsid in cls.IDS:
    alog.debug(f'Registering file system: {fsid}')
    _FS_REGISTRY[fsid] = cls

try_register(importer, modname, parent=None)

Import a module and register the FileSystem classes it exports.

Parameters:

Name Type Description Default
importer

The package finder providing find_spec().

required
modname

Name of the module to import.

required
parent

Optional parent package name used to import the module as parent.modname.

None

Returns:

Type Description

The imported module, or None when the import failed.

Source code in py_misc_utils/gfs.py
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
def try_register(importer, modname, parent=None):
  """Import a module and register the FileSystem classes it exports.

  Args:
    importer: The package finder providing find_spec().
    modname: Name of the module to import.
    parent: Optional parent package name used to import the module as
      parent.modname.

  Returns:
    The imported module, or None when the import failed.
  """
  try:
    if parent is None:
      spec = importer.find_spec(modname)
      module = importlib.util.module_from_spec(spec)
      spec.loader.exec_module(module)
    else:
      module = importlib.import_module(f'{parent}.{modname}')

    file_systems = getattr(module, 'FILE_SYSTEMS', ())
    for cls in file_systems:
      register_fs(cls)

    return module
  except ImportError as ex:
    alog.verbose(f'Unable to import file system module "{modname}": {ex}')

register_fs_from_path(path, parent=None)

Register the FileSystem classes of the *_fs modules of a directory.

Parameters:

Name Type Description Default
path

Directory path to scan for *_fs modules.

required
parent

Optional parent package name used to import the modules as parent.modname.

None
Source code in py_misc_utils/gfs.py
791
792
793
794
795
796
797
798
799
800
801
def register_fs_from_path(path, parent=None):
  """Register the FileSystem classes of the *_fs modules of a directory.

  Args:
    path: Directory path to scan for *_fs modules.
    parent: Optional parent package name used to import the modules as
      parent.modname.
  """
  for importer, modname, _ in pkgutil.iter_modules(path=path):
    if modname.endswith('_fs'):
      try_register(importer, modname, parent=parent)

register_modules()

Register the built-in and GFS_PATH FileSystem backends.

The py_misc_utils.fs backends are registered once, plus any module found in the colon-separated GFS_PATH environment variable.

Example
import os
import tempfile

from py_misc_utils import gfs

# Point GFS_PATH at a directory holding custom *_fs.py backends.
plugin_dir = tempfile.mkdtemp()
os.environ['GFS_PATH'] = plugin_dir

gfs.register_modules()

# The built-in backends are available after the registration.
fs = gfs.get_proto_fs('file')

print(fs.ID)
Source code in py_misc_utils/gfs.py
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
@ro.run_once
def register_modules():
  """Register the built-in and GFS_PATH FileSystem backends.

  The py_misc_utils.fs backends are registered once, plus any module
  found in the colon-separated GFS_PATH environment variable.

  Example:
    import os
    import tempfile

    from py_misc_utils import gfs

    # Point GFS_PATH at a directory holding custom *_fs.py backends.
    plugin_dir = tempfile.mkdtemp()
    os.environ['GFS_PATH'] = plugin_dir

    gfs.register_modules()

    # The built-in backends are available after the registration.
    fs = gfs.get_proto_fs('file')

    print(fs.ID)
  """
  import py_misc_utils.fs as pyfs

  register_fs_from_path(pyfs.__path__, parent='py_misc_utils.fs')

  gfs_path = os.getenv('GFS_PATH')
  if gfs_path:
    for path in gfs_path.split(':'):
      register_fs_from_path(path)

get_proto_fs(proto, **kwargs)

Create a FileSystem instance for a protocol.

Parameters:

Name Type Description Default
proto

Protocol name of the backend to instantiate.

required
**kwargs

Constructor keyword arguments forwarded to the backend.

{}

Returns:

Type Description

The instantiated FileSystem backend.

Raises:

Type Description
ValueError

When the protocol is not registered.

Source code in py_misc_utils/gfs.py
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
def get_proto_fs(proto, **kwargs):
  """Create a FileSystem instance for a protocol.

  Args:
    proto: Protocol name of the backend to instantiate.
    **kwargs: Constructor keyword arguments forwarded to the backend.

  Returns:
    The instantiated FileSystem backend.

  Raises:
    ValueError: When the protocol is not registered.
  """
  register_modules()

  cls = _FS_REGISTRY.get(proto)
  tas.check_is_not_none(cls, msg=f'Protocol "{proto}" not registered')

  return cls(**kwargs)

resolve_fs(path, **kwargs)

Resolve the FileSystem backend and normalized path of a path/URL.

Parameters:

Name Type Description Default
path

Path or URL to resolve.

required
**kwargs

Keyword arguments consumed by the cache settings (cache_dir, cache_iface) and forwarded to the backend constructor.

{}

Returns:

Type Description

A tuple with the FileSystem backend and the normalized path.

Source code in py_misc_utils/gfs.py
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
def resolve_fs(path, **kwargs):
  """Resolve the FileSystem backend and normalized path of a path/URL.

  Args:
    path: Path or URL to resolve.
    **kwargs: Keyword arguments consumed by the cache settings
      (cache_dir, cache_iface) and forwarded to the backend constructor.

  Returns:
    A tuple with the FileSystem backend and the normalized path.
  """
  proto = get_proto(path)

  cachedir = chf.get_cache_dir(kwargs.pop('cache_dir', cache_dir()))

  cache_iface = kwargs.pop('cache_iface', None)
  if cache_iface is None:
    cache_iface = chf.CacheInterface(cachedir)

  fs = get_proto_fs(proto, cache_iface=cache_iface, cache_dir=cachedir, **kwargs)

  return fs, fs.norm_url(path)