GitHub

LiveFileSystem

API reference for LiveFileSystem.

The host's file system. watch asks a WatchBackend first (the one provided where the stream runs, else backend), then the operating system's change notification (WatchfilesBackend, with the watch extra); without the extra it polls every watch_interval.

Functions

__init__

__init__(*, backend=None, watch_interval=DEFAULT_WATCH_INTERVAL) -> None
ParameterTypeDescription
backendWatchBackendService | None = None
watch_intervalDuration = DEFAULT_WATCH_INTERVAL
def __init__(
    self,
    *,
    backend: WatchBackendService | None = None,
    watch_interval: Duration = DEFAULT_WATCH_INTERVAL,
) -> None:
    self._backend = backend
    self._watch_interval = watch_interval

access

access(path, *, readable=False, writable=False) -> Effect[None, PlatformError]
ParameterTypeDescription
pathstr
readablebool = False
writablebool = False

Returns Effect[None, PlatformError]

def access(
    self, path: str, *, readable: bool = False, writable: bool = False
) -> Effect[None, PlatformError]:
    return run("access", path, lambda: _access(path, readable, writable))

copy

copy(from_path, to_path, *, overwrite=False, preserve_timestamps=False) -> Effect[None, PlatformError]
ParameterTypeDescription
from_pathstr
to_pathstr
overwritebool = False
preserve_timestampsbool = False

Returns Effect[None, PlatformError]

def copy(
    self,
    from_path: str,
    to_path: str,
    *,
    overwrite: bool = False,
    preserve_timestamps: bool = False,
) -> Effect[None, PlatformError]:
    return run(
        "copy",
        from_path,
        lambda: copy_tree(from_path, to_path, overwrite, preserve_timestamps),
    )

copy_file

copy_file(from_path, to_path) -> Effect[None, PlatformError]
ParameterTypeDescription
from_pathstr
to_pathstr

Returns Effect[None, PlatformError]

def copy_file(self, from_path: str, to_path: str) -> Effect[None, PlatformError]:
    return run("copy_file", from_path, lambda: _copy_file(from_path, to_path))

chmod

chmod(path, mode) -> Effect[None, PlatformError]
ParameterTypeDescription
pathstr
modeint

Returns Effect[None, PlatformError]

def chmod(self, path: str, mode: int) -> Effect[None, PlatformError]:
    return run("chmod", path, lambda: os.chmod(path, mode))

chown

chown(path, uid, gid) -> Effect[None, PlatformError]
ParameterTypeDescription
pathstr
uidint
gidint

Returns Effect[None, PlatformError]

def chown(self, path: str, uid: int, gid: int) -> Effect[None, PlatformError]:
    return run("chown", path, lambda: os.chown(path, uid, gid))
link(from_path, to_path) -> Effect[None, PlatformError]
ParameterTypeDescription
from_pathstr
to_pathstr

Returns Effect[None, PlatformError]

def link(self, from_path: str, to_path: str) -> Effect[None, PlatformError]:
    return run("link", from_path, lambda: os.link(from_path, to_path))

lstat

lstat(path) -> Effect[FileInfo, PlatformError]
ParameterTypeDescription
pathstr

Returns Effect[FileInfo, PlatformError]

def lstat(self, path: str) -> Effect[FileInfo, PlatformError]:
    return run("lstat", path, lambda: file_info(os.lstat(path)))

make_directory

make_directory(path, *, recursive=False, mode=511) -> Effect[None, PlatformError]
ParameterTypeDescription
pathstr
recursivebool = False
modeint = 511

Returns Effect[None, PlatformError]

def make_directory(
    self, path: str, *, recursive: bool = False, mode: int = 0o777
) -> Effect[None, PlatformError]:
    return run("make_directory", path, lambda: _make_directory(path, recursive, mode))

make_temp_directory

make_temp_directory(*, directory=None, prefix='') -> Effect[str, PlatformError]
ParameterTypeDescription
directorystr | None = None
prefixstr = ''

Returns Effect[str, PlatformError]

def make_temp_directory(
    self, *, directory: str | None = None, prefix: str = ""
) -> Effect[str, PlatformError]:
    return run("make_temp_directory", directory, lambda: _temp_directory(directory, prefix))

make_temp_directory_scoped

make_temp_directory_scoped(*, directory=None, prefix='') -> Effect[str, PlatformError, Scope]
ParameterTypeDescription
directorystr | None = None
prefixstr = ''

Returns Effect[str, PlatformError, Scope]

def make_temp_directory_scoped(
    self, *, directory: str | None = None, prefix: str = ""
) -> Effect[str, PlatformError, Scope]:
    method = "make_temp_directory_scoped"
    return acquire_release(
        run(method, directory, lambda: _temp_directory(directory, prefix)),
        lambda path, _exit: run(method, path, lambda: _remove(path, True, True)).or_die(),
    )

make_temp_file

make_temp_file(*, directory=None, prefix='', suffix='') -> Effect[str, PlatformError]
ParameterTypeDescription
directorystr | None = None
prefixstr = ''
suffixstr = ''

Returns Effect[str, PlatformError]

def make_temp_file(
    self, *, directory: str | None = None, prefix: str = "", suffix: str = ""
) -> Effect[str, PlatformError]:
    return run("make_temp_file", directory, lambda: _temp_file(directory, prefix, suffix))

make_temp_file_scoped

make_temp_file_scoped(*, directory=None, prefix='', suffix='') -> Effect[str, PlatformError, Scope]
ParameterTypeDescription
directorystr | None = None
prefixstr = ''
suffixstr = ''

Returns Effect[str, PlatformError, Scope]

def make_temp_file_scoped(
    self, *, directory: str | None = None, prefix: str = "", suffix: str = ""
) -> Effect[str, PlatformError, Scope]:
    method = "make_temp_file_scoped"
    return acquire_release(
        run(method, directory, lambda: _temp_file(directory, prefix, suffix)),
        lambda path, _exit: run(
            method, path, lambda: _remove(os.path.dirname(path), True, True)
        ).or_die(),
    )

open

open(path, *, flag='r', mode=438, no_follow=False) -> Effect[File, PlatformError, Scope]
ParameterTypeDescription
pathstr
flagOpenFlag = 'r'
modeint = 438
no_followbool = False

Returns Effect[File, PlatformError, Scope]

def open(
    self, path: str, *, flag: OpenFlag = "r", mode: int = 0o666, no_follow: bool = False
) -> Effect[File, PlatformError, Scope]:
    flags = _open_flags(flag)
    if no_follow:
        no_follow_flag: int = getattr(os, "O_NOFOLLOW", 0)
        if os.name == "nt" or not no_follow_flag:
            return fail(
                bad_argument(
                    module="FileSystem",
                    method="open",
                    description="no_follow is not supported on this platform",
                )
            )
        flags |= no_follow_flag
    return acquire_release(
        run("open", path, lambda: os.open(path, flags, mode)),
        lambda fd, _exit: run("open", fd, lambda: os.close(fd)).or_die(),
    ).map(lambda fd: LiveFile(fd, append=flag.startswith("a")))

read_directory

read_directory(path, *, recursive=False) -> Effect[list[str], PlatformError]
ParameterTypeDescription
pathstr
recursivebool = False

Returns Effect[list[str], PlatformError]

def read_directory(
    self, path: str, *, recursive: bool = False
) -> Effect[list[str], PlatformError]:
    return run("read_directory", path, lambda: _read_directory(path, recursive))

read_directory_entries

read_directory_entries(path) -> Effect[tuple[DirectoryEntry, ...], PlatformError]
ParameterTypeDescription
pathstr

Returns Effect[tuple[DirectoryEntry, ...], PlatformError]

def read_directory_entries(
    self, path: str
) -> Effect[tuple[DirectoryEntry, ...], PlatformError]:
    return run("read_directory_entries", path, lambda: _read_directory_entries(path))

read_file

read_file(path) -> Effect[bytes, PlatformError]
ParameterTypeDescription
pathstr

Returns Effect[bytes, PlatformError]

def read_file(self, path: str) -> Effect[bytes, PlatformError]:
    return run("read_file", path, lambda: _read(path))
read_link(path) -> Effect[str, PlatformError]
ParameterTypeDescription
pathstr

Returns Effect[str, PlatformError]

def read_link(self, path: str) -> Effect[str, PlatformError]:
    return run("read_link", path, lambda: os.readlink(path))

real_path

real_path(path) -> Effect[str, PlatformError]
ParameterTypeDescription
pathstr

Returns Effect[str, PlatformError]

def real_path(self, path: str) -> Effect[str, PlatformError]:
    return run("real_path", path, lambda: os.path.realpath(path, strict=True))

remove

remove(path, *, recursive=False, force=False) -> Effect[None, PlatformError]
ParameterTypeDescription
pathstr
recursivebool = False
forcebool = False

Returns Effect[None, PlatformError]

def remove(
    self, path: str, *, recursive: bool = False, force: bool = False
) -> Effect[None, PlatformError]:
    return run("remove", path, lambda: _remove(path, recursive, force))

rename

rename(old_path, new_path) -> Effect[None, PlatformError]
ParameterTypeDescription
old_pathstr
new_pathstr

Returns Effect[None, PlatformError]

def rename(self, old_path: str, new_path: str) -> Effect[None, PlatformError]:
    return run("rename", old_path, lambda: os.replace(old_path, new_path))

stat

stat(path) -> Effect[FileInfo, PlatformError]
ParameterTypeDescription
pathstr

Returns Effect[FileInfo, PlatformError]

def stat(self, path: str) -> Effect[FileInfo, PlatformError]:
    return run("stat", path, lambda: file_info(os.stat(path)))
symlink(from_path, to_path) -> Effect[None, PlatformError]
ParameterTypeDescription
from_pathstr
to_pathstr

Returns Effect[None, PlatformError]

def symlink(self, from_path: str, to_path: str) -> Effect[None, PlatformError]:
    return run("symlink", from_path, lambda: os.symlink(from_path, to_path))

truncate

truncate(path, length=0) -> Effect[None, PlatformError]
ParameterTypeDescription
pathstr
lengthint = 0

Returns Effect[None, PlatformError]

def truncate(self, path: str, length: int = 0) -> Effect[None, PlatformError]:
    return run("truncate", path, lambda: os.truncate(path, length))

utimes

utimes(path, atime, mtime) -> Effect[None, PlatformError]
ParameterTypeDescription
pathstr
atimedatetime | float
mtimedatetime | float

Returns Effect[None, PlatformError]

def utimes(
    self, path: str, atime: datetime | float, mtime: datetime | float
) -> Effect[None, PlatformError]:
    return run("utimes", path, lambda: os.utime(path, ns=(_nanos(atime), _nanos(mtime))))

watch

watch(path, *, recursive=False, on_ready=None) -> Stream[WatchEvent, PlatformError]
ParameterTypeDescription
pathstr
recursivebool = False
on_readyCallable[[], None] | None = None

Returns Stream[WatchEvent, PlatformError]

def watch(
    self, path: str, *, recursive: bool = False, on_ready: Callable[[], None] | None = None
) -> Stream[WatchEvent, PlatformError]:
    def make() -> Generator[Effect[Any, PlatformError], Any, Stream[WatchEvent, PlatformError]]:
        info = yield from self.stat(path)
        caller = yield from service_option(WatchBackend)
        for backend in (option.get_or_none(caller) or self._backend, _NATIVE):
            if backend is not None:
                found = backend.register(path, info, recursive=recursive, on_ready=on_ready)
                if found is not None:
                    return found
        return poll(
            path,
            directory=info.type == "Directory",
            recursive=recursive,
            on_ready=on_ready,
            interval=self._watch_interval,
        )

    return stream_.unwrap(gen(make))

write_file

write_file(path, data, *, flag='w', mode=438) -> Effect[None, PlatformError]
ParameterTypeDescription
pathstr
databytes
flagOpenFlag = 'w'
modeint = 438

Returns Effect[None, PlatformError]

def write_file(
    self, path: str, data: bytes, *, flag: OpenFlag = "w", mode: int = 0o666
) -> Effect[None, PlatformError]:
    return run("write_file", path, lambda: _write(path, data, flag, mode))

glob

glob(pattern, *, root=None, exclude=(), dot=False) -> Effect[list[str], PlatformError]

The paths below root (the working directory) matching the pyfect.glob pattern and none of exclude: /-separated, relative to root (absolute for an absolute pattern), depth first with each directory's entries sorted by name. Wildcards skip names that start with . unless the segment does or dot is set, and dir/** includes dir. ** does not follow symbolic links to directories; a link named by another segment is followed. Excluded directories are not read; an entry whose type cannot be told (a broken link) counts as a file.

Failing to read the root or a leading literal directory fails; missing paths give nothing, and unreadable directories reached through wildcards are skipped. Wildcards are case-sensitive; leading literal segments use stat, so they follow the file system's case rules and results keep the pattern's spelling. Built from read_directory_entries, stat and read_link.

ParameterTypeDescription
patternstr
rootstr | None = None
excludetuple[str, ...] = ()
dotbool = False

Returns Effect[list[str], PlatformError]

def glob(
    self,
    pattern: str,
    *,
    root: str | None = None,
    exclude: tuple[str, ...] = (),
    dot: bool = False,
) -> Effect[list[str], PlatformError]:
    """The paths below ``root`` (the working directory) matching the
    ``pyfect.glob`` pattern and none of ``exclude``: ``/``-separated,
    relative to ``root`` (absolute for an absolute pattern), depth
    first with each directory's entries sorted by name. Wildcards skip
    names that start with ``.`` unless the segment does or ``dot`` is
    set, and ``dir/**`` includes ``dir``. ``**`` does not follow
    symbolic links to directories; a link named by another segment is
    followed. Excluded directories are not read; an entry whose type
    cannot be told (a broken link) counts as a file.

    Failing to read the root or a leading literal directory fails;
    missing paths give nothing, and unreadable directories reached
    through wildcards are skipped. Wildcards are case-sensitive; leading
    literal segments use ``stat``, so they follow the file system's case
    rules and results keep the pattern's spelling. Built from
    ``read_directory_entries``, ``stat`` and ``read_link``."""
    return glob_walk(self, pattern, root=root, exclude=exclude, dot=dot)

exists

exists(path) -> Effect[bool, PlatformError]

Whether path exists; errors other than NotFound fail.

ParameterTypeDescription
pathstr

Returns Effect[bool, PlatformError]

def exists(self, path: str) -> Effect[bool, PlatformError]:
    """Whether ``path`` exists; errors other than ``NotFound`` fail."""
    return self.access(path).map(lambda _: True).catch_all(_false_if_not_found)

read_file_string

read_file_string(path, encoding='utf-8') -> Effect[str, PlatformError]

The file decoded as encoding; undecodable bytes become U+FFFD and a leading byte order mark is dropped, as JavaScript's TextDecoder does. An unknown encoding is a BadArgument.

ParameterTypeDescription
pathstr
encodingstr = 'utf-8'

Returns Effect[str, PlatformError]

def read_file_string(self, path: str, encoding: str = "utf-8") -> Effect[str, PlatformError]:
    """The file decoded as ``encoding``; undecodable bytes become
    U+FFFD and a leading byte order mark is dropped, as JavaScript's
    ``TextDecoder`` does. An unknown encoding is a ``BadArgument``."""
    return self.read_file(path).flat_map(lambda data: _decode(data, encoding))

write_file_string

write_file_string(path, data, *, flag='w', mode=438) -> Effect[None, PlatformError]

data as UTF-8 (a lone surrogate becomes U+FFFD).

ParameterTypeDescription
pathstr
datastr
flagOpenFlag = 'w'
modeint = 438

Returns Effect[None, PlatformError]

def write_file_string(
    self, path: str, data: str, *, flag: OpenFlag = "w", mode: int = 0o666
) -> Effect[None, PlatformError]:
    """``data`` as UTF-8 (a lone surrogate becomes U+FFFD)."""
    return self.write_file(path, text_encode(data), flag=flag, mode=mode)

stream

stream(path, *, offset=0, bytes_to_read=None, chunk_size=DEFAULT_CHUNK_SIZE) -> Stream[bytes, PlatformError]

The file's bytes from offset, chunk_size at a time, up to bytes_to_read of them. The file opens when the stream starts and closes when it ends.

ParameterTypeDescription
pathstr
offsetint = 0
bytes_to_readint | None = None
chunk_sizeint = DEFAULT_CHUNK_SIZE

Returns Stream[bytes, PlatformError]

def stream(
    self,
    path: str,
    *,
    offset: int = 0,
    bytes_to_read: int | None = None,
    chunk_size: int = DEFAULT_CHUNK_SIZE,
) -> Stream[bytes, PlatformError]:
    """The file's bytes from ``offset``, ``chunk_size`` at a time, up to
    ``bytes_to_read`` of them. The file opens when the stream starts and
    closes when it ends."""

    def make() -> Generator[
        Effect[Any, PlatformError, Scope], Any, Stream[bytes, PlatformError]
    ]:
        file = yield from self.open(path, flag="r")
        if offset:
            yield from file.seek(offset, "start")
        return stream_.from_pull(succeed(_reader(file, bytes_to_read, chunk_size)))

    return stream_.unwrap(gen(make))

sink

sink(path, *, flag='w', mode=438) -> Sink[None, bytes, Never, PlatformError]

A sink writing each chunk it reads to the file, opened (truncated by default) when the sink starts.

ParameterTypeDescription
pathstr
flagOpenFlag = 'w'
modeint = 438

Returns Sink[None, bytes, Never, PlatformError]

def sink(
    self, path: str, *, flag: OpenFlag = "w", mode: int = 0o666
) -> Sink[None, bytes, Never, PlatformError]:
    """A sink writing each chunk it reads to the file, opened (truncated
    by default) when the sink starts."""
    return unwrap_sink(
        self.open(path, flag=flag, mode=mode).map(lambda file: for_each(file.write_all))
    )