Skip to content

fs_base

Base class for filesystem abstractions.

This module defines DirEntry, a namedtuple for directory listing entries, and FsBase, an abstract base class that all filesystem implementations must subclass. FsBase provides common path/mode utilities and declares the abstract interface for filesystem operations.

Example
import os
import tempfile

from py_misc_utils import gfs

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

with open(path, 'w') as fd:
  fd.write('hello')

fs = gfs.get_proto_fs('file')
entry = fs.stat(path)

print(entry.name, entry.st_size)

FsBase

Bases: ABC

Abstract base class for filesystem implementations.

Provides common mode-parsing class methods and default implementations for some operations, while declaring abstract methods that subclasses must implement: stat, open, remove, rename, mkdir, makedirs, rmdir, rmtree, list, put_file, get_file, as_local, link and symlink.

Source code in py_misc_utils/fs_base.py
 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
class FsBase(abc.ABC):
  """Abstract base class for filesystem implementations.

  Provides common mode-parsing class methods and default implementations for
  some operations, while declaring abstract methods that subclasses must
  implement: stat, open, remove, rename, mkdir, makedirs, rmdir, rmtree,
  list, put_file, get_file, as_local, link and symlink.
  """

  def __init__(self, cache_iface=None, **kwargs):
    """Initialize the filesystem base.

    Args:
      cache_iface: Optional cache interface object. Defaults to None.
      **kwargs: Additional keyword arguments stored in self._kwargs.
    """
    super().__init__()
    self._cache_iface = cache_iface
    self._kwargs = kwargs

  @classmethod
  def read_mode(cls, mode):
    """Check if the mode opens the file for reading.

    Args:
      mode: The file mode string.

    Returns:
      True if 'r' is in mode and '+' is not, False otherwise.
    """
    return 'r' in mode and not '+' in mode

  @classmethod
  def write_mode(cls, mode):
    """Check if the mode opens the file for writing.

    Args:
      mode: The file mode string.

    Returns:
      True if mode contains 'w', 'a', or '+', False otherwise.
    """
    return any(c in mode for c in 'wa+')

  @classmethod
  def truncate_mode(cls, mode):
    """Check if the mode opens the file for writing with truncation.

    Args:
      mode: The file mode string.

    Returns:
      True if 'w' is in mode and '+' is not, False otherwise.
    """
    return 'w' in mode and '+' not in mode

  @classmethod
  def append_mode(cls, mode):
    """Check if the mode opens the file for appending.

    Args:
      mode: The file mode string.

    Returns:
      True if 'a' is in mode, False otherwise.
    """
    return 'a' in mode

  @classmethod
  def text_mode(cls, mode):
    """Check if the mode opens the file in text mode.

    Args:
      mode: The file mode string.

    Returns:
      True if 'b' is not in mode (text mode), False otherwise.
    """
    return 'b' not in mode

  @classmethod
  def seek_stream(cls, mode, stream):
    """Seek the stream to the appropriate position based on mode.

    For append mode, seeks to end of file. Otherwise seeks to the beginning.

    Args:
      mode: The file mode string.
      stream: The file stream object to seek.
    """
    stream.seek(0, os.SEEK_END if cls.append_mode(mode) else os.SEEK_SET)

  def norm_url(self, url):
    """Normalize a URL for this filesystem.

    The base implementation returns the URL unchanged. Subclasses may override
    to perform filesystem-specific normalization.

    Args:
      url: The URL string to normalize.

    Returns:
      The normalized URL string.
    """
    return url

  def exists(self, url):
    """Check if a URL exists in this filesystem.

    Args:
      url: The URL string to check.

    Returns:
      True if the URL exists, False otherwise.
    """
    try:
      self.stat(url)

      return True
    # stat() backends raise backend-specific errors (and some return None on
    # missing URLs - tracked defect): any failure answers False, never raises.
    except Exception:  # noqa: BLE001
      return False

  def isdir(self, url):
    """Check if a URL is a directory.

    Args:
      url: The URL string to check.

    Returns:
      True if the URL is a directory, False otherwise.
    """
    try:
      de = self.stat(url)

      return st.S_ISDIR(de.st_mode)
    except Exception:  # noqa: BLE001
      return False

  def isfile(self, url):
    """Check if a URL is a regular file.

    Args:
      url: The URL string to check.

    Returns:
      True if the URL is a regular file, False otherwise.
    """
    try:
      de = self.stat(url)

      return st.S_ISREG(de.st_mode)
    # stat() backends raise backend-specific errors (and some return None on
    # missing URLs - tracked defect): any failure answers False, never raises.
    except Exception:  # noqa: BLE001
      return False

  def copyfile(self, url, dest_fs, dest_url):
    """Copy a file from this filesystem to another filesystem.

    Args:
      url: The source URL.
      dest_fs: The destination FsBase instance.
      dest_url: The destination URL.
    """
    dest_fs.put_file(dest_url, self.get_file(url))

  @abc.abstractmethod
  def stat(self, url):
    """Return stat information for the given URL.

    Args:
      url: The URL string to stat.

    Returns:
      A DirEntry namedtuple with stat information.
    """
    ...

  @abc.abstractmethod
  def open(self, url, mode, **kwargs):
    """Open a file at the given URL with the specified mode.

    Args:
      url: The URL string to open.
      mode: The file mode string.
      **kwargs: Additional keyword arguments.

    Returns:
      A file-like object.
    """
    ...

  @abc.abstractmethod
  def remove(self, url):
    """Remove the file at the given URL.

    Args:
      url: The URL string to remove.
    """
    ...

  @abc.abstractmethod
  def rename(self, src_url, dest_url):
    """Rename/move a file from src_url to dest_url.

    Args:
      src_url: The source URL string.
      dest_url: The destination URL string.
    """
    ...

  def replace(self, src_url, dest_url):
    """Replace the file at dest_url with the file at src_url.

    The base implementation delegates to rename(). Subclasses may override
    for atomic replace semantics.

    Args:
      src_url: The source URL string.
      dest_url: The destination URL string.
    """
    self.rename(src_url, dest_url)

  @abc.abstractmethod
  def mkdir(self, url, mode=None):
    """Create a directory at the given URL.

    Args:
      url: The URL string for the directory.
      mode: Optional permission mode. Defaults to None.
    """
    ...

  @abc.abstractmethod
  def makedirs(self, url, mode=None, exist_ok=None):
    """Create a directory and all parent directories at the given URL.

    Args:
      url: The URL string for the directory.
      mode: Optional permission mode. Defaults to None.
      exist_ok: If True, do not raise if the directory exists. Defaults to None.
    """
    ...

  @abc.abstractmethod
  def rmdir(self, url):
    """Remove an empty directory at the given URL.

    Args:
      url: The URL string of the directory to remove.
    """
    ...

  @abc.abstractmethod
  def rmtree(self, url, ignore_errors=None):
    """Recursively remove a directory tree at the given URL.

    Args:
      url: The URL string of the directory tree to remove.
      ignore_errors: If True, ignore errors during removal. Defaults to None.
    """
    ...

  @abc.abstractmethod
  def list(self, url):
    """List the contents of a directory at the given URL.

    Args:
      url: The URL string of the directory to list.

    Yields:
      A DirEntry namedtuple for every entry of the directory.
    """
    ...

  @abc.abstractmethod
  def put_file(self, url, data_gen):
    """Write data to a file at the given URL.

    Args:
      url: The URL string to write to.
      data_gen: A generator or iterable producing data chunks.
    """
    ...

  @abc.abstractmethod
  def get_file(self, url):
    """Read and return the contents of a file at the given URL.

    Args:
      url: The URL string to read from.

    Returns:
      The file contents.
    """
    ...

  @abc.abstractmethod
  def as_local(self, url):
    """Return a local filesystem path for the given URL, if available.

    Args:
      url: The URL string to resolve.

    Returns:
      A local path string, or None if not available.
    """
    ...

  @abc.abstractmethod
  def link(self, src_url, dest_url):
    """Create a hard link from src_url to dest_url.

    Args:
      src_url: The source URL string.
      dest_url: The destination URL string.
    """
    ...

  @abc.abstractmethod
  def symlink(self, src_url, dest_url):
    """Create a symbolic link from src_url to dest_url.

    Args:
      src_url: The source URL string.
      dest_url: The destination URL string.
    """
    ...

read_mode(mode) classmethod

Check if the mode opens the file for reading.

Parameters:

Name Type Description Default
mode

The file mode string.

required

Returns:

Type Description

True if 'r' is in mode and '+' is not, False otherwise.

Source code in py_misc_utils/fs_base.py
65
66
67
68
69
70
71
72
73
74
75
@classmethod
def read_mode(cls, mode):
  """Check if the mode opens the file for reading.

  Args:
    mode: The file mode string.

  Returns:
    True if 'r' is in mode and '+' is not, False otherwise.
  """
  return 'r' in mode and not '+' in mode

write_mode(mode) classmethod

Check if the mode opens the file for writing.

Parameters:

Name Type Description Default
mode

The file mode string.

required

Returns:

Type Description

True if mode contains 'w', 'a', or '+', False otherwise.

Source code in py_misc_utils/fs_base.py
77
78
79
80
81
82
83
84
85
86
87
@classmethod
def write_mode(cls, mode):
  """Check if the mode opens the file for writing.

  Args:
    mode: The file mode string.

  Returns:
    True if mode contains 'w', 'a', or '+', False otherwise.
  """
  return any(c in mode for c in 'wa+')

truncate_mode(mode) classmethod

Check if the mode opens the file for writing with truncation.

Parameters:

Name Type Description Default
mode

The file mode string.

required

Returns:

Type Description

True if 'w' is in mode and '+' is not, False otherwise.

Source code in py_misc_utils/fs_base.py
89
90
91
92
93
94
95
96
97
98
99
@classmethod
def truncate_mode(cls, mode):
  """Check if the mode opens the file for writing with truncation.

  Args:
    mode: The file mode string.

  Returns:
    True if 'w' is in mode and '+' is not, False otherwise.
  """
  return 'w' in mode and '+' not in mode

append_mode(mode) classmethod

Check if the mode opens the file for appending.

Parameters:

Name Type Description Default
mode

The file mode string.

required

Returns:

Type Description

True if 'a' is in mode, False otherwise.

Source code in py_misc_utils/fs_base.py
101
102
103
104
105
106
107
108
109
110
111
@classmethod
def append_mode(cls, mode):
  """Check if the mode opens the file for appending.

  Args:
    mode: The file mode string.

  Returns:
    True if 'a' is in mode, False otherwise.
  """
  return 'a' in mode

text_mode(mode) classmethod

Check if the mode opens the file in text mode.

Parameters:

Name Type Description Default
mode

The file mode string.

required

Returns:

Type Description

True if 'b' is not in mode (text mode), False otherwise.

Source code in py_misc_utils/fs_base.py
113
114
115
116
117
118
119
120
121
122
123
@classmethod
def text_mode(cls, mode):
  """Check if the mode opens the file in text mode.

  Args:
    mode: The file mode string.

  Returns:
    True if 'b' is not in mode (text mode), False otherwise.
  """
  return 'b' not in mode

seek_stream(mode, stream) classmethod

Seek the stream to the appropriate position based on mode.

For append mode, seeks to end of file. Otherwise seeks to the beginning.

Parameters:

Name Type Description Default
mode

The file mode string.

required
stream

The file stream object to seek.

required
Source code in py_misc_utils/fs_base.py
125
126
127
128
129
130
131
132
133
134
135
@classmethod
def seek_stream(cls, mode, stream):
  """Seek the stream to the appropriate position based on mode.

  For append mode, seeks to end of file. Otherwise seeks to the beginning.

  Args:
    mode: The file mode string.
    stream: The file stream object to seek.
  """
  stream.seek(0, os.SEEK_END if cls.append_mode(mode) else os.SEEK_SET)

norm_url(url)

Normalize a URL for this filesystem.

The base implementation returns the URL unchanged. Subclasses may override to perform filesystem-specific normalization.

Parameters:

Name Type Description Default
url

The URL string to normalize.

required

Returns:

Type Description

The normalized URL string.

Source code in py_misc_utils/fs_base.py
137
138
139
140
141
142
143
144
145
146
147
148
149
def norm_url(self, url):
  """Normalize a URL for this filesystem.

  The base implementation returns the URL unchanged. Subclasses may override
  to perform filesystem-specific normalization.

  Args:
    url: The URL string to normalize.

  Returns:
    The normalized URL string.
  """
  return url

exists(url)

Check if a URL exists in this filesystem.

Parameters:

Name Type Description Default
url

The URL string to check.

required

Returns:

Type Description

True if the URL exists, False otherwise.

Source code in py_misc_utils/fs_base.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def exists(self, url):
  """Check if a URL exists in this filesystem.

  Args:
    url: The URL string to check.

  Returns:
    True if the URL exists, False otherwise.
  """
  try:
    self.stat(url)

    return True
  # stat() backends raise backend-specific errors (and some return None on
  # missing URLs - tracked defect): any failure answers False, never raises.
  except Exception:  # noqa: BLE001
    return False

isdir(url)

Check if a URL is a directory.

Parameters:

Name Type Description Default
url

The URL string to check.

required

Returns:

Type Description

True if the URL is a directory, False otherwise.

Source code in py_misc_utils/fs_base.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def isdir(self, url):
  """Check if a URL is a directory.

  Args:
    url: The URL string to check.

  Returns:
    True if the URL is a directory, False otherwise.
  """
  try:
    de = self.stat(url)

    return st.S_ISDIR(de.st_mode)
  except Exception:  # noqa: BLE001
    return False

isfile(url)

Check if a URL is a regular file.

Parameters:

Name Type Description Default
url

The URL string to check.

required

Returns:

Type Description

True if the URL is a regular file, False otherwise.

Source code in py_misc_utils/fs_base.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def isfile(self, url):
  """Check if a URL is a regular file.

  Args:
    url: The URL string to check.

  Returns:
    True if the URL is a regular file, False otherwise.
  """
  try:
    de = self.stat(url)

    return st.S_ISREG(de.st_mode)
  # stat() backends raise backend-specific errors (and some return None on
  # missing URLs - tracked defect): any failure answers False, never raises.
  except Exception:  # noqa: BLE001
    return False

copyfile(url, dest_fs, dest_url)

Copy a file from this filesystem to another filesystem.

Parameters:

Name Type Description Default
url

The source URL.

required
dest_fs

The destination FsBase instance.

required
dest_url

The destination URL.

required
Source code in py_misc_utils/fs_base.py
203
204
205
206
207
208
209
210
211
def copyfile(self, url, dest_fs, dest_url):
  """Copy a file from this filesystem to another filesystem.

  Args:
    url: The source URL.
    dest_fs: The destination FsBase instance.
    dest_url: The destination URL.
  """
  dest_fs.put_file(dest_url, self.get_file(url))

stat(url) abstractmethod

Return stat information for the given URL.

Parameters:

Name Type Description Default
url

The URL string to stat.

required

Returns:

Type Description

A DirEntry namedtuple with stat information.

Source code in py_misc_utils/fs_base.py
213
214
215
216
217
218
219
220
221
222
223
@abc.abstractmethod
def stat(self, url):
  """Return stat information for the given URL.

  Args:
    url: The URL string to stat.

  Returns:
    A DirEntry namedtuple with stat information.
  """
  ...

open(url, mode, **kwargs) abstractmethod

Open a file at the given URL with the specified mode.

Parameters:

Name Type Description Default
url

The URL string to open.

required
mode

The file mode string.

required
**kwargs

Additional keyword arguments.

{}

Returns:

Type Description

A file-like object.

Source code in py_misc_utils/fs_base.py
225
226
227
228
229
230
231
232
233
234
235
236
237
@abc.abstractmethod
def open(self, url, mode, **kwargs):
  """Open a file at the given URL with the specified mode.

  Args:
    url: The URL string to open.
    mode: The file mode string.
    **kwargs: Additional keyword arguments.

  Returns:
    A file-like object.
  """
  ...

remove(url) abstractmethod

Remove the file at the given URL.

Parameters:

Name Type Description Default
url

The URL string to remove.

required
Source code in py_misc_utils/fs_base.py
239
240
241
242
243
244
245
246
@abc.abstractmethod
def remove(self, url):
  """Remove the file at the given URL.

  Args:
    url: The URL string to remove.
  """
  ...

rename(src_url, dest_url) abstractmethod

Rename/move a file from src_url to dest_url.

Parameters:

Name Type Description Default
src_url

The source URL string.

required
dest_url

The destination URL string.

required
Source code in py_misc_utils/fs_base.py
248
249
250
251
252
253
254
255
256
@abc.abstractmethod
def rename(self, src_url, dest_url):
  """Rename/move a file from src_url to dest_url.

  Args:
    src_url: The source URL string.
    dest_url: The destination URL string.
  """
  ...

replace(src_url, dest_url)

Replace the file at dest_url with the file at src_url.

The base implementation delegates to rename(). Subclasses may override for atomic replace semantics.

Parameters:

Name Type Description Default
src_url

The source URL string.

required
dest_url

The destination URL string.

required
Source code in py_misc_utils/fs_base.py
258
259
260
261
262
263
264
265
266
267
268
def replace(self, src_url, dest_url):
  """Replace the file at dest_url with the file at src_url.

  The base implementation delegates to rename(). Subclasses may override
  for atomic replace semantics.

  Args:
    src_url: The source URL string.
    dest_url: The destination URL string.
  """
  self.rename(src_url, dest_url)

mkdir(url, mode=None) abstractmethod

Create a directory at the given URL.

Parameters:

Name Type Description Default
url

The URL string for the directory.

required
mode

Optional permission mode. Defaults to None.

None
Source code in py_misc_utils/fs_base.py
270
271
272
273
274
275
276
277
278
@abc.abstractmethod
def mkdir(self, url, mode=None):
  """Create a directory at the given URL.

  Args:
    url: The URL string for the directory.
    mode: Optional permission mode. Defaults to None.
  """
  ...

makedirs(url, mode=None, exist_ok=None) abstractmethod

Create a directory and all parent directories at the given URL.

Parameters:

Name Type Description Default
url

The URL string for the directory.

required
mode

Optional permission mode. Defaults to None.

None
exist_ok

If True, do not raise if the directory exists. Defaults to None.

None
Source code in py_misc_utils/fs_base.py
280
281
282
283
284
285
286
287
288
289
@abc.abstractmethod
def makedirs(self, url, mode=None, exist_ok=None):
  """Create a directory and all parent directories at the given URL.

  Args:
    url: The URL string for the directory.
    mode: Optional permission mode. Defaults to None.
    exist_ok: If True, do not raise if the directory exists. Defaults to None.
  """
  ...

rmdir(url) abstractmethod

Remove an empty directory at the given URL.

Parameters:

Name Type Description Default
url

The URL string of the directory to remove.

required
Source code in py_misc_utils/fs_base.py
291
292
293
294
295
296
297
298
@abc.abstractmethod
def rmdir(self, url):
  """Remove an empty directory at the given URL.

  Args:
    url: The URL string of the directory to remove.
  """
  ...

rmtree(url, ignore_errors=None) abstractmethod

Recursively remove a directory tree at the given URL.

Parameters:

Name Type Description Default
url

The URL string of the directory tree to remove.

required
ignore_errors

If True, ignore errors during removal. Defaults to None.

None
Source code in py_misc_utils/fs_base.py
300
301
302
303
304
305
306
307
308
@abc.abstractmethod
def rmtree(self, url, ignore_errors=None):
  """Recursively remove a directory tree at the given URL.

  Args:
    url: The URL string of the directory tree to remove.
    ignore_errors: If True, ignore errors during removal. Defaults to None.
  """
  ...

list(url) abstractmethod

List the contents of a directory at the given URL.

Parameters:

Name Type Description Default
url

The URL string of the directory to list.

required

Yields:

Type Description

A DirEntry namedtuple for every entry of the directory.

Source code in py_misc_utils/fs_base.py
310
311
312
313
314
315
316
317
318
319
320
@abc.abstractmethod
def list(self, url):
  """List the contents of a directory at the given URL.

  Args:
    url: The URL string of the directory to list.

  Yields:
    A DirEntry namedtuple for every entry of the directory.
  """
  ...

put_file(url, data_gen) abstractmethod

Write data to a file at the given URL.

Parameters:

Name Type Description Default
url

The URL string to write to.

required
data_gen

A generator or iterable producing data chunks.

required
Source code in py_misc_utils/fs_base.py
322
323
324
325
326
327
328
329
330
@abc.abstractmethod
def put_file(self, url, data_gen):
  """Write data to a file at the given URL.

  Args:
    url: The URL string to write to.
    data_gen: A generator or iterable producing data chunks.
  """
  ...

get_file(url) abstractmethod

Read and return the contents of a file at the given URL.

Parameters:

Name Type Description Default
url

The URL string to read from.

required

Returns:

Type Description

The file contents.

Source code in py_misc_utils/fs_base.py
332
333
334
335
336
337
338
339
340
341
342
@abc.abstractmethod
def get_file(self, url):
  """Read and return the contents of a file at the given URL.

  Args:
    url: The URL string to read from.

  Returns:
    The file contents.
  """
  ...

as_local(url) abstractmethod

Return a local filesystem path for the given URL, if available.

Parameters:

Name Type Description Default
url

The URL string to resolve.

required

Returns:

Type Description

A local path string, or None if not available.

Source code in py_misc_utils/fs_base.py
344
345
346
347
348
349
350
351
352
353
354
@abc.abstractmethod
def as_local(self, url):
  """Return a local filesystem path for the given URL, if available.

  Args:
    url: The URL string to resolve.

  Returns:
    A local path string, or None if not available.
  """
  ...

Create a hard link from src_url to dest_url.

Parameters:

Name Type Description Default
src_url

The source URL string.

required
dest_url

The destination URL string.

required
Source code in py_misc_utils/fs_base.py
356
357
358
359
360
361
362
363
364
@abc.abstractmethod
def link(self, src_url, dest_url):
  """Create a hard link from src_url to dest_url.

  Args:
    src_url: The source URL string.
    dest_url: The destination URL string.
  """
  ...

Create a symbolic link from src_url to dest_url.

Parameters:

Name Type Description Default
src_url

The source URL string.

required
dest_url

The destination URL string.

required
Source code in py_misc_utils/fs_base.py
366
367
368
369
370
371
372
373
374
@abc.abstractmethod
def symlink(self, src_url, dest_url):
  """Create a symbolic link from src_url to dest_url.

  Args:
    src_url: The source URL string.
    dest_url: The destination URL string.
  """
  ...