Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-std

Source of release 0.7.0

0.7.0 / src / files / text.lucb

#==============================================================================================
#
#   text - Whole-file text and directories by counted path
#
#   DESCRIPTION:
#       UTF-8 file text read, replaced and created whole, and directories ensured, for paths
#       given as counted text (a Luce `str`), validated before they reach the filesystem.
#
#==============================================================================================

import utf8

func text_path(path: str) -> str!:
    if path.length == 0 or not utf8.valid(path.bytes):
        error(invalid_options, "a path must be nonempty UTF-8")
    for byte in path.bytes:
        if byte == 0:
            error(invalid_options, "a path cannot contain NUL")
    return try strings.copy(path)

# mark: Reading and writing text ==============================================================

## The file's text, refusing a file over `limit` bytes or one that is not UTF-8. The result
## owns its storage: Luce copies it into a `str`; a Base caller calls `release()`.
pub func read_text(path: str, limit: usize = 4194304) -> interop.Owned[str]!:
    let native = try text_path(path)
    defer strings.release(native)
    let data = try read((c.str)native, limit)
    if not utf8.valid(data.value):
        data.release()
        error(invalid_options, "the file is not valid UTF-8")
    return interop.Owned[str]((str)data.value, data.owner)

## Replace atomically in the destination directory, preserving existing mode bits.
## Resolve an existing symlink to its target before replacement.
pub func write_text(path: str, text: str) -> !:
    if not utf8.valid(text.bytes):
        error(invalid_options, "file text must be valid UTF-8")
    let native = try text_path(path)
    defer strings.release(native)
    let resolved = canonical((c.str)native) catch failure:
        if failure.code != missing:
            error(failure.code, failure.message)
        recover try owned.copy_text(native)
    defer resolved.release()
    let info = metadata((c.str)resolved.value) catch failure:
        if failure.code != missing:
            error(failure.code, failure.message)
        recover Metadata(kind = FileKind.regular, permissions = 420)
    if info.kind != FileKind.regular:
        error(invalid_options, "text can only replace a regular file")
    try write_atomic((c.str)resolved.value, text.bytes, permissions = info.permissions)

## Publish complete UTF-8 text only if the destination is unused. A racing
## creator is refused atomically; existing files and symlinks are never replaced.
pub func create_text(path: str, text: str = "") -> !:
    if not utf8.valid(text.bytes):
        error(invalid_options, "file text must be valid UTF-8")
    let native = try text_path(path)
    defer strings.release(native)
    var replacement = try Replacement.prepare((c.str)native, 420, false)
    defer replacement.destroy()
    try io.write_all(&replacement.temporary, text.bytes)
    try replacement.finish((c.str)native, false, none)

# mark: Directories ===========================================================================

## Make sure `path` is a directory, creating it and any missing parents, like `mkdir -p`.
## An existing directory is fine; an existing file in the way is not_directory.
pub func ensure_directory(path: str) -> !:
    let native = try text_path(path)
    defer strings.release(native)
    try ensure_tree((c.str)native)

func ensure_tree(path: c.str) -> !:
    create_directory(path) catch failure:
        if failure.code == missing:
            let parent = paths.directory((str)path)
            if parent == "." or parent == (str)path or paths.root((str)path) == parent:
                error(failure.code, failure.message)
            let parent_name = try strings.copy(parent)
            defer strings.release(parent_name)
            try ensure_tree((c.str)parent_name)
            create_directory(path) catch again:
                if again.code != already_exists:
                    error(again.code, again.message)
        elif failure.code != already_exists:
            error(failure.code, failure.message)
    if (try metadata(path)).kind != FileKind.directory:
        error(not_directory, "the existing path is not a directory")

## The user's home directory: HOME on POSIX, USERPROFILE on Windows.
pub func home_directory() -> interop.Owned[str]!:
    let home = try io.path.user()
    if home.length == 0:
        error(invalid_options, "the user home directory is empty")
    return try owned.copy_text(home)