Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-std

Source of release 0.7.0

0.7.0 / src / files / workspace.lucb

#==============================================================================================
#
#   workspace - Canonical paths and temporary trees
#
#   DESCRIPTION:
#       Filesystem identity and owned temporary directory trees. Paths are answered as owned
#       results, which Luce copies and Base callers release.
#
#==============================================================================================

extern func realpath(path: c.str, output: u8*?) -> u8*?
extern func release_realpath as "free"(path: void*)
extern func fcntl(descriptor: i32, command: i32, ...) -> i32

## macOS: `open` for a descriptor that only names the entry (no read access needed, and a
## FIFO does not block), and `fcntl`'s question for the path the descriptor names.
let event_only: i32 = 32768
let get_path: i32 = 50

## Resolve an existing entry through symlinks to its absolute filesystem path.
## Windows extended DOS/UNC prefixes are normalized to ordinary UTF-8 paths with
## forward slashes. This resolves identity; it does not fold case or authorize access.
## The result owns its NUL-terminated text: Base callers read `.value` and call `release()`.
pub func canonical(path: c.str) -> interop.Owned[str]!:
    if platform.windows:
        let handle = try windows_path_handle(path, true)
        defer _ = CloseHandle(handle)
        let wide = try new u16[32768] ---
        defer free(wide)
        let count = GetFinalPathNameByHandleW(handle, wide.data, (u32)wide.length, 0)
        if count == 0 or count >= wide.length:
            error(failed, "the filesystem path could not be resolved")
        var start: usize = 0
        if count >= 4 and wide[0] == 92 and wide[1] == 92 and wide[2] == 63 and wide[3] == 92:
            start = 4
            if count >= 8 and wide[4] == 85 and wide[5] == 78 and wide[6] == 67 and wide[7] == 92:
                wide[6] = 92
                start = 6
        let result = try windows_text.narrow(wide[start..<(usize)count], invalid_options)
        let bytes = (u8*)result.bytes.data
        for index in 0..<result.length:
            if bytes[index] == 92:
                bytes[index] = '/'
        return try owned.adopt_text(result)
    elif platform.macos:
        # realpath lists every directory on the way to learn each name's case; the
        # descriptor's path is the same answer from the kernel at once
        # (an entry that cannot be opened so, such as a socket, goes to realpath, whose
        # answer or failure stands)
        let descriptor = posix_open(path, event_only)
        if descriptor >= 0:
            defer _ = close(descriptor)
            var buffer: u8[1024] = ---
            if fcntl(descriptor, get_path, &buffer[0]) >= 0:
                var length: usize = 0
                while length < buffer.length and buffer[length] != 0:
                    length += 1
                return try owned.copy_text((str)buffer[..<length])
        let resolved = realpath(path, none) else error(classify_error(c.errno()), "the filesystem path could not be resolved")
        defer release_realpath((void*)resolved)
        return try owned.copy_text((str)(c.str)resolved)
    else:
        let resolved = realpath(path, none) else error(classify_error(c.errno()), "the filesystem path could not be resolved")
        defer release_realpath((void*)resolved)
        return try owned.copy_text((str)(c.str)resolved)

## Atomically create an unused directory with 128 random filename bits, answering its
## path as an owned text. The parent must already exist.
pub func create_temporary_directory(parent: c.str, permissions: u32 = 448) -> interop.Owned[str]!:
    let candidate = try paths.join((str)parent, ".luce-00000000000000000000000000000000")
    errdefer candidate.release()
    let digits = "0123456789abcdef"
    let data = (u8*)candidate.value.bytes.data
    let suffix = candidate.value.length - 32
    var attempt: usize = 0
    while attempt < 128:
        var random: u8[16]
        try os.random_bytes(random)
        for index in 0..<random.length:
            data[suffix + index * 2] = digits.bytes[random[index] >> 4]
            data[suffix + index * 2 + 1] = digits.bytes[random[index] & 15]
        create_directory((c.str)candidate.value, permissions) catch failure:
            if failure.code == already_exists:
                attempt += 1
                continue
            error(failure.code, failure.message)
        return candidate
    error(already_exists, "no unused temporary directory name was found")

## Remove this entry and its children. Symlinks are unlinked rather than followed;
## a missing entry is already removed. Other failures stop and remain reportable.
pub func remove_tree(path: c.str) -> !:
    let info = metadata(path, follow_symlinks = false) catch failure:
        if failure.code == missing:
            return
        error(failure.code, failure.message)
    if info.kind != FileKind.directory:
        try remove_file(path)
        return
    let names = try list(path)
    defer names.release()
    for name in names.value:
        let child = try paths.join((str)path, name)
        defer child.release()
        try remove_tree((c.str)child.value)
    try remove_directory(path)

## Own one directory tree, removed with everything in it on close. Borrow this owner;
## copying it does not copy ownership. close reports cleanup failures and keeps ownership
## for a retry; destroy makes a final attempt and always releases the pathname. Luce sees
## it as an object, `with files.TemporaryDirectory() as directory:`, removed on close.
pub struct TemporaryDirectory:
    var name: str

    ## Create a temporary directory under `parent`, or the system's temporary directory.
    pub func init(parent: c.str = "") -> !:
        let directory = (str)parent if ((str)parent).length > 0 else io.path.temp()
        let created = try create_temporary_directory((c.str)directory)
        defer created.release()
        var name: str
        with memory.heap:
            name = strings.copy(created.value) catch failure:
                remove_directory((c.str)created.value) catch cleanup:
                    _ = cleanup
                error(failure.code, failure.message)
        self.name = name

    ## The directory's path, NUL-terminated, valid until close or destroy.
    pub func path() -> str:
        return self.name

    func release_name():
        if self.name.length > 0:
            with memory.heap:
                strings.release(self.name)
            self.name = ""

    ## Remove the directory tree; reports the first failure.
    pub func close() -> !:
        if self.name.length == 0:
            return
        try remove_tree((c.str)self.name)
        self.release_name()

    ## Best-effort removal, releasing memory regardless.
    pub func destroy():
        self.close() catch failure:
            _ = failure
        self.release_name()

## The interop type of a temporary directory.
pub let temporary_directory_type: interop.Type[TemporaryDirectory] = interop.Type[TemporaryDirectory]("TemporaryDirectory", TemporaryDirectory.destroy, closeable = true)