sysl

The fs module

sysl.fs — files and paths, in three tiers; IoError and why it is an enum; and requires os, the capability that decides whether the module exists at all.

Every declaration in sysl.fs, with its signature: the generated API page. This page is the argument — what the module is for, and how its pieces fit; that one is the list.

sysl.fs is the first module in this section that a target may simply not have. Its files open with two lines rather than one:

module sysl.fs
@requires(os)

Nothing here is language, and nothing here can be given a body on a target with no filesystem under it: every call it makes goes through the hooks of sysl.fs.sys, which a hosted target’s C library answers and a bare machine answers only if the program does (below). So the clause is not a warning — it is a fact about which module exists, and it is checked at the import:

@no_os

import sysl.fs.exists

print(exists("/tmp"))
this reaches 'sysl.fs', which requires 'os', and this module declared 'no os' — an environment capability gates which modules exist, so a module that gave one up may not reach one that needs it

That is the difference between os and alloc worth holding on to. alloc is checked on what a module calls, because the standard library has allocating and non-allocating halves running through the middle of it. os is checked on the module boundary, because it decides which modules exist at all — there is no half of sysl.fs that works without one.

Three tiers, and the line between them is the allocator

tiernameswhat it costs
whole fileread_text, read_bytes, write_text, write_bytes, append_text, append_bytes, write_text_atomic, write_bytes_atomicstorage the size of the file — allocates by nature
open fileopen, create, append, open_update, create_update, and File‘s membersa buffer the caller already has
pathexists, readable, writable, executable, is_file, is_dir, is_link, size_of, metadata, link_metadata, set_permissions, set_owner, set_link_owner, set_modified, set_times, link_set_times, space, symlink, read_link, hard_link, canonicalize, get_xattr, set_xattr, remove_xattr, list_xattrs and their link_ forms, make_dir, make_dir_all, remove_file, remove_dir, remove_dir_all, rename, pending_name, publish_file, publish_dir, copy_file, truncate, current_dir, set_current_dir, temp_root, temp_dir, make_temp_dirone C call each, or a loop over them

Reading a whole file is asking for storage the size of the file, so the top tier could not have been written any other way. Keeping it apart from File is what lets the middle tier stay honest: opening and reading in chunks needs only a buffer the caller brought, and works in a module that must not allocate.

The whole-file tier

import sysl.fs.{write_text, read_text, append_text, read_bytes, remove_file, exists}
import sysl.process.pid

var path = s"/tmp/sysl-fs-doc-1-${pid()}.txt"

write_text(path, "hello\n").unwrap()

print(read_text(path).unwrap().len)

append_text(path, "again\n").unwrap()

print(read_bytes(path).unwrap().len)
prints(read_text(path).unwrap())

remove_file(path).unwrap()

print(exists(path))
6
12
hello
again
false

Each of these opens, does the one thing, and closes — and closes through defer, so the handle is released down the failing paths too. That is the idiom the module is written to demonstrate: a scope releases what the scope said it would. A destructor is the other way to say it and wants the handle behind a &T; these functions never let one escape, so the scope is enough.

read_bytes reads in chunks and grows rather than sizing itself from the file’s length first. That costs a little copying and buys the case that matters — a file being written while this reads it, and anything whose length is not a fact until the read ends. The loop stops on the first empty read, and asks afterwards whether the reading ended badly, which is the split Reader was built around.

Bytes that are not UTF-8 are an error, InvalidUtf8, carrying the offset of the first one that is not. A file is input, and a program reading one it did not write cannot have ruled out the byte that breaks it — so this is a Result and not a trap, as errors draws the line. The offset counts from the start of the file:

import sysl.fs.{read_text, remove_file, write_bytes}
import sysl.process.pid

val f = s"/tmp/sysl-fs-doc-not-utf8-${pid()}.txt"

write_bytes(f, [u8('o'), u8('k'), 255]).unwrap()

read_text(f) match
    Ok(s) -> print("read", s)
    Err(e) -> print("refused:", e)

remove_file(f).unwrap()
refused: not UTF-8 at byte 2

A caller that wants the text anyway — replacing what does not decode, or reading the file as some other encoding — reads read_bytes and decides for itself, with from_utf8 or anything else.

A file the whole-file tier makes can be born with its permission bits. write_bytes, write_text, append_bytes, append_text and the two _atomic writers take a last mode, 0o666 by default, with exactly the rules of create‘s (§ One reading of an entry): the process umask narrows it, bits above the twelve permission bits are dropped, a target with no permission bits ignores it, and a file that is already there keeps the mode it has — its contents are replaced or added to, not the file. A secret is owner-only from the moment it exists, with no window before a set_permissions, and a failure answers the same error, the OS’s reason included, whatever mode was asked for. The _atomic writers are the exception to keeping a mode, by their nature: they put a new file in the old one’s place, and that file has the mode asked for.

import sysl.fs.{append_text, metadata, read_text, remove_file, set_permissions, write_text}
import sysl.process.pid

val path = s"/tmp/sysl-fs-doc-write-mode-${pid()}.txt"

write_text(path, "key\n", 0o600).unwrap()

print(metadata(path).unwrap().permissions() == 0o600)

set_permissions(path, 0o640).unwrap()
append_text(path, "more\n", 0o600).unwrap()
write_text(path, "replaced\n", 0o600).unwrap()

print(metadata(path).unwrap().permissions() == 0o640, read_text(path).unwrap().len)

remove_file(path).unwrap()
true
true 9

Writing where somebody else is reading

write_text truncates and then writes, so for as long as the write takes, a reader of the path finds half a file under the name it trusts. Where the path is shared — a cache entry, a configuration file another process reloads, a binary about to be run — write to a pending name beside it and rename that into place. A rename within one directory is one step: a reader sees the whole of the old file or the whole of the new one, never a mixture and never a moment with nothing there.

import sysl.fs.{entries, make_dir, make_temp_dir, pending_name, publish_dir, read_text, remove_dir_all, write_text, write_text_atomic}
import sysl.path.join

val dir = make_temp_dir("sysl-fs-doc-publish").unwrap()
val config = join(dir, "config.toml")

write_text_atomic(config, "retries = 3\n").unwrap()
write_text_atomic(config, "retries = 5\n").unwrap()

prints(read_text(config).unwrap())
print(entries(dir).unwrap().len())

val cache = join(dir, "cache")

for who in ["first", "second"]
    val staged = pending_name(cache)

    make_dir(staged).unwrap()
    write_text(join(staged, "built-by"), who).unwrap()
    publish_dir(staged, cache).unwrap()

print(read_text(join(cache, "built-by")).unwrap())
print(entries(dir).unwrap().len())

remove_dir_all(dir).unwrap()
retries = 5
1
first
2

write_text_atomic and write_bytes_atomic are the whole pattern in one call, and a failure anywhere — the write, the close, the rename — removes the pending file and answers the first error, so the directory holds exactly what it held before. That is why the listing above says 1: the pending names never outlive the call.

The pending name is beside the target, not in the temporary directory. A rename only moves a file within one filesystem, and nothing says the destination shares one with /tmp. pending_name(target) is the target plus a suffix carrying a token drawn once per process — sixty-four bits of kernel entropy, not a process id — and a count taken once per call, so two processes never agree on one and neither do two calls of one process. Use it directly for whatever is built in several steps, and hand the result to publish_file or publish_dir.

publish_dir treats losing a race as success. Two writers of one entry are building the same thing; a rename refuses to replace a directory that holds anything, so the first one to finish is never disturbed, and the second removes its own copy and answers Ok — which is why the cache above still says first. Only a rename that fails with no directory at the target afterwards is reported. Clearing away the losing copy walks a tree, which is written over the hooks like everything else here.

IoError

enum IoError
    NotFound
    PermissionDenied
    AlreadyExists
    NotADirectory
    IsADirectory
    DirectoryNotEmpty
    TooManyOpenFiles
    NoSpaceLeft
    Interrupted
    NotOpen
    NotPermitted
    InvalidUtf8(offset: usize)
    NoAttribute
    Other(code: int)

    code(self) -> int
    message(self) -> string

impl Display for IoError

from_errno(code: int) -> IoError

Every Result this module hands back carries one. It is an enum rather than a bare int for the reason Result carries its error as a type parameter at all: a caller that wants to act on why wants to match, and a match over named cases is exhaustive where a comparison against a number is a guess that compiled.

The cases are the ones a program branches on, and everything else arrives as Other carrying the number. A library that mapped every errno to a name of its own would be a table nobody could keep current and a program could not extend — and the number is what a reader looks up anyway.

NotPermitted is EPERM (code 1) and PermissionDenied is EACCES (13), and they are not one case: the first is an operation this process may not perform at all, the second a file whose mode or owner refuses it.

InvalidUtf8 is the one case no errno produces. It is what read_text, entries, read_link, canonicalize, current_dir, temp_dir and temp_file answer when bytes that had to be text are not UTF-8, and its offset is the byte at which the decode stopped. Its code() is EILSEQ (92 on macOS, 84 on Linux); two of them are equal when they stopped at the same byte, and one is never equal to an Other.

NoAttribute is an extended attribute that is not there: ENOATTR, 93, on macOS and ENODATA, 61, on Linux, whose C libraries spell the one as the other. It is a case of its own so that a missing attribute is not mistaken for a missing file.

code() answers for every case, not only Other: the named ones hand back the code they were recognised from, which keeps the question answerable without a second table. message() is a sentence in the terms the operation was asked in rather than in C’s, and the Display impl is what makes print(e) say it. An Other says the platform’s sentence for its code — what the C library’s strerror_r gives, so EILSEQ is “Illegal byte sequence” on macOS — and a code the library does not know comes back in its words for that (“Unknown error: 4242”). A target with no C library says what the words for an error number below give:

import sysl.fs.read_text

read_text("/tmp/sysl-fs-doc-missing.txt") match
    Ok(s) -> print("read", s.len)
    Err(e) -> print("refused:", e, e.code())
refused: no such file or directory 2

errno is read at the failure, not wherever the caller got round to asking. The one place it is read is the hosted answer to sysl.fs.sys‘s hooks, straight after the C call that failed, and what crosses back is the number; sysl.fs turns it into an IoError once. A File that latches a failure keeps the code it failed with, so a close afterwards cannot overwrite it.

from_errno is that one table, and it is public so that a program calling C for itself reports a failure exactly as the library does: from_errno(2) is NotFound, and a code no case names is Other(code). Read errno straight after the call that set it, and e == NotFound means one thing whoever made the call:

import sysl.fs.{from_errno, open, NotFound, Other}

extern "rmdir" c_rmdir(path: *u8) -> int

#if bsd
extern "__error" errno_location() -> *i32
#else
extern "__errno_location" errno_location() -> *i32
#endif

val mine = if c_rmdir(c"/no-such-dir") != 0 then from_errno(errno_location()[0]) else Other(0)

print(mine == NotFound, mine == open("/no-such-dir").unwrap_err(), from_errno(4242).code())
true true 4242

The words for an error number

An Other‘s words are asked of whatever answers the filesystem, through one more hook of sysl.fs.sys, sysl_fs_error_text(code, into, room, got) -> int: zero having copied the words into into and their length to got, anything else having none to give. It is the one hook a program never has to answer — the library answers it on every target, over strerror_r on a POSIX host and with no words on a machine with no C library — so a kernel whose error numbers are its own can say what they mean, and one that never thought about it is asked nothing.

A code the supplier has no words for goes to the library’s own table, and only then to error N — and words that are not UTF-8 count as none. The table holds the numbers every platform agrees on and nothing past them: V7 Unix’s 1 to 34, which have meant the same thing on every Unix since (11 aside, which a BSD spends on EDEADLK), and EAGAIN, ENOTEMPTY and EILSEQ at this target’s own number. A table claiming more would put Linux’s words to a BSD’s codes. So on a bare machine EBUSY says “device or resource busy” with no help from anybody. A hosted target that is not POSIX numbers its errors its own way and is not given the table.

A program’s own answer displaces the library’s, here on a host as on a board — so 16, which it declines, comes from the table rather than from the C library:

import sysl.fs.IoError

@export("sysl_fs_error_text")
words(code: int, into: *u8, room: usize, got: *usize) -> int
    if code != 77 then return -1

    val w = "the disk is resting"

    for i in 0..<w.bytes.len do into[i] = w.bytes[i]

    *got = w.bytes.len
    0
end words

print(IoError.Other(77).message())
print(IoError.Other(16).message())
print(IoError.Other(4242).message())
the disk is resting
device or resource busy
error 4242

File

struct File
    closed(*self) -> bool
    flush(*self) -> Result[unit, IoError]
    close(*self) -> Result[unit, IoError]
    tell(*self) -> Result[long, IoError]
    seek(*self, to: long) -> Result[unit, IoError]
    size(*self) -> Result[long, IoError]
    at_end(*self) -> bool
    fd(self) -> Result[int, IoError]
    map(*self) -> Result[&Mapped, IoError]

impl Fallible for File
impl Reader for File
impl Writer for File

open(path: string) -> Result[File, IoError]          // an existing file, for reading
create(path: string, mode: u32 = 0o666) -> Result[File, IoError] // makes one, or empties one that was there
append(path: string, mode: u32 = 0o666) -> Result[File, IoError] // writes at the end
open_update(path: string) -> Result[File, IoError]   // read and write; fails if it is not there
create_update(path: string, mode: u32 = 0o666) -> Result[File, IoError] // read and write; empties what was there
open_with(path: string, options: OpenOptions) -> Result[File, IoError] // exactly the options asked

struct OpenOptions                                   // open_options() is the empty set
    read(self) -> OpenOptions
    write(self) -> OpenOptions
    append(self) -> OpenOptions                      // implies write
    truncate(self) -> OpenOptions                    // needs write
    create(self) -> OpenOptions                      // O_CREAT
    create_new(self) -> OpenOptions                  // O_CREAT | O_EXCL
    sync(self) -> OpenOptions                        // O_SYNC
    dsync(self) -> OpenOptions                       // O_DSYNC
    nofollow(self) -> OpenOptions                    // O_NOFOLLOW
    mode(self, bits: u32) -> OpenOptions             // a created file's permission bits

A File is a descriptor from sysl.fs.sys with a buffer in front of it, and the buffer is written in sysl. A Writer that reached the operating system once per write would make rendering into a file cost a system call per fragment, and the rendering surface writes in fragments — so small writes collect until they are worth a call, small reads are served from one larger one, and a read or write as large as the buffer goes straight through. A position, a size, a read after a write and a write after a read all answer as though nothing were held back. The five functions above are named for what they mean rather than for the flags each becomes; O_CREAT and its siblings differ between C libraries, and are translated once, by the hosted answer to the hooks.

fd() lends the descriptor, for a call this module does not make — to poll it, to fcntl it, to hand it to C. Lent, not given: the File still closes it — explicitly, or when its last copy goes — bytes written and not yet flushed have not reached it, and a closed file answers NotOpen rather than a number that may by now be somebody else’s.

into_raw_fd() gives the descriptor away, as Rust’s does, for a program that hands it to C for longer than the File lives. What is buffered is handed over and what was read ahead is given back first, so the number stands where the file did; from then on every copy of the file is closed, and closing the number is the caller’s to do.

import sysl.fs.{create_update, read_text, remove_file}
import sysl.process.pid

val path = s"/tmp/sysl-fs-doc-raw-${pid()}.txt"
var f = create_update(path).unwrap()

f.write("kept".bytes)

val n = f.into_raw_fd().unwrap()

print(n >= 0, f.fd().is_err(), read_text(path).unwrap())
remove_file(path).unwrap()
true true kept

Saying the options one at a time

open_with opens a file with exactly the options in an OpenOptions, for the combinations the five names above do not cover. open_options() is the empty set, and each member answers the set with one more thing asked, so a set reads as a chain and is a value a program can keep and open several files with. Every option reaches the operating system or the open fails; none is dropped quietly.

  • read and write say how the file is used; asking neither reads it. append writes at the end of whatever is there at each write and implies write.
  • truncate empties a file that is there, and needs write: without it the open is refused with Other(22) before the file is touched, since POSIX leaves O_TRUNC on a read-only open unspecified.
  • create makes the file where it is missing. create_new makes it and fails with AlreadyExists where anything is there — a file, a directory, a symbolic link, even a dangling one — with the check and the making one step (O_CREAT | O_EXCL). It is what a lock file or a never-overwrite save needs, and what exists followed by create is not.
  • sync makes each write wait until the data and the metadata needed to read it back are on the device (O_SYNC); dsync waits for the data, and the metadata only where reading the data needs it (O_DSYNC, or O_SYNC where a C library has no O_DSYNC). They are the per-write form of full_sync and sync_data below.
  • nofollow refuses a symbolic link at the last component (O_NOFOLLOW), and the error answers refused_link(), as a Dir‘s refusals do. A link in a directory above the last component is still followed — confining a whole path is Dir‘s work — and a chain of links that loops is refused the same way, since the kernel gives the two one code. Without nofollow such a loop is an ordinary Other with the platform’s ELOOP.
  • mode is the permission bits a file this open creates is born with, 0o666 unless asked and narrowed by the umask, exactly as create‘s; it applies only when the file is created, and bits above the twelve permission bits are dropped.

A target whose C library has no O_SYNC or no O_NOFOLLOW answers not supported on this target to an open asking for it.

import sysl.fs.{open_with, open_options, metadata, read_text, remove_file, symlink, write_text}
import sysl.process.pid

val path = s"/tmp/sysl-fs-doc-new-${pid()}.txt"
val link = s"/tmp/sysl-fs-doc-new-${pid()}.link"
val fresh = open_options().write().create_new().mode(0o600)

var f = open_with(path, fresh).unwrap()

f.write("first".bytes)
f.close().unwrap()

print(metadata(path).unwrap().permissions() == 0o600)
print(open_with(path, fresh).unwrap_err())

symlink(path, link).unwrap()

val refused = open_with(link, open_options().write().truncate().nofollow()).unwrap_err()

print(refused.refused_link(), refused)
print(read_text(path).unwrap())

remove_file(link).unwrap()
remove_file(path).unwrap()
true
already exists
true the path goes through a symbolic link
first

A file opened with sync or dsync is an ordinary File; each write that reaches the descriptor returns once it is on the device, so a buffered write is durable from the flush that sends it.

import sysl.fs.{open_with, open_options, read_text, remove_file}
import sysl.process.pid

val path = s"/tmp/sysl-fs-doc-dsync-${pid()}.log"

var log = open_with(path, open_options().append().create().dsync()).unwrap()

log.write("entry 1\n".bytes)
log.flush().unwrap()
log.close().unwrap()

print(read_text(path).unwrap() == "entry 1\n")
remove_file(path).unwrap()
true

It is a Reader and a Writer, whole

import sysl.fs.{write_text, open, remove_file}
import sysl.io.lines
import sysl.process.pid

var path = s"/tmp/sysl-fs-doc-3-${pid()}.txt"

write_text(path, "alpha\nbeta\ngamma\n").unwrap()

var f = open(path).unwrap()

for line in lines(&f)
    prints("[")
    prints(line)
    prints("]")

prints("\n")
print(f.failed(), f.at_end())

f.close().unwrap()
remove_file(path).unwrap()
[alpha][beta][gamma]
false true

lines(&f) works over a file with nothing in sysl.fs knowing about lines, because impl Reader for File is the trait unmodified. Everything that renders into a sink renders into a file for the same reason.

That is also why Fallible is a required trait rather than a member each of them declares. failed takes no arguments, so a failed from Reader and another from Writer would be two members of one name on one type and a call could not say which it meant — on a file, which is both. One shared latch leaves a single answer that each of them reaches.

Reaching a trait member on a File needs no import of the trait, since impl Reader for File is one the program can see (Reaching a member through its trait):

import sysl.fs.{open, write_text, remove_file}
import sysl.process.pid

val path = s"/tmp/sysl-fs-doc-3b-${pid()}.txt"

write_text(path, "abcdef").unwrap()

var f = open(path).unwrap()
var window: [4]u8

print(f.read(window).len)
remove_file(path).unwrap()
4

Position and size

import sysl.fs.{write_text, open, size_of, remove_file}
import sysl.io.Reader
import sysl.process.pid

var path = s"/tmp/sysl-fs-doc-4-${pid()}.txt"

write_text(path, "0123456789").unwrap()

print(size_of(path).unwrap())

var f = open(path).unwrap()
var window: [4]u8

f.seek(6).unwrap()

var got = f.read(window)

print(f.tell().unwrap(), got.len, got[0])
print(f.size().unwrap())

f.close().unwrap()
remove_file(path).unwrap()
10
10 4 54
10

size asks the file rather than measuring it. It was a seek to the end and back — four calls to answer one question — because the alternative was fstat, and struct stat is laid out differently by each platform’s headers: a program transcribing one holds numbers nothing checks, and being wrong about them reads the wrong bytes rather than failing. A shim beside the module reads the header and one field crosses, so the refusal costs nothing here any more. It never moves the position, which is why tell still reports 10 afterwards — where the seek version moved it and put it back, leaving it at the end of the file if anything failed in between.

Where there is no shim, the seek is still what runs. sysl.fs requires os rather than posix, so it reaches a Windows target that has no per-OS directory here — and fseek/ftell are ISO C, so that path goes on working exactly as it did.

size_of(path) is the same question without an open file in hand; it opens, asks, and closes, so a missing file answers NotFound rather than zero — the distinction a caller sizing a buffer needs and the one a bare number could not carry.

A file is a positioned store too

A File implements ReadAt and WriteAt, so a codec or a filesystem written against them reads and writes a file with no adapter. Its Error is IoError.

import sysl.fs.{write_text, open_update, read_text, remove_file}
import sysl.io.{Reader, ReadAt, WriteAt}
import sysl.process.pid

var path = s"/tmp/sysl-fs-doc-pio-${pid()}.txt"

write_text(path, "0123456789").unwrap()

var f = open_update(path).unwrap()
var window: [3]u8

print(f.read_at(4, window).unwrap()[0], f.tell().unwrap())
print(f.write_at(8, "XY".bytes).unwrap(), f.tell().unwrap())
f.write("A".bytes)
f.sync().unwrap()
print(read_text(path).unwrap(), f.extent().unwrap())

f.close().unwrap()
remove_file(path).unwrap()
52 0
2 0
A1234567XY 10

Neither moves the position: they are the platform’s pread and pwrite, past the buffer, so they mix freely with read and write. What the buffer holds is settled first. A read at an offset sees every byte the program has written, because what is held back is handed over before it. A write at an offset gives up what was read ahead, since it may have changed those bytes. sync hands over what is held back and then asks the device to keep it (fsync). extent is size as the u64 the traits speak in. An offset beyond what the platform’s offset type holds is Other(22), EINVAL, as the platform answers it. On Linux, a file opened with append puts a positioned write at the end whatever the offset; that is the platform’s own pwrite, and it is left showing rather than hidden.

Closing, and using a file after it

import sysl.fs.{create, remove_file}
import sysl.io.Reader
import sysl.process.pid

var path = s"/tmp/sysl-fs-doc-5-${pid()}.txt"
var f = create(path).unwrap()

f.close().unwrap()

print(f.closed(), f.at_end())
print(f.close().is_ok())
print(f.seek(0).unwrap_err(), f.seek(0).unwrap_err().code())

var window: [4]u8
var got = f.read(window)

print(got.len, f.failed())

remove_file(path).unwrap()
true true
true
the file is not open 9
0 true

Four rules are in that output.

A File closes itself when its last copy goes, as Rust’s does: out of scope, out of a Buf, with the struct that held it. What is still buffered is handed over first, and then the descriptor is closed. The state every copy shares has a destructor, so a file that dies where no defer could be written — inside a container, inside a struct inside a container — is closed all the same.

close is still the call to make where the answer matters. Handing over what was buffered is where a full disk finally reports, and a destructor has nobody to report to, so a failure there is dropped as Rust’s BufWriter drops it. defer f.close() remains a correct way to write it, and is no longer needed to stop a leak.

close is idempotent, and the second call is not merely tolerated — it is the case defer creates. A function that closes on one path and defers the close for the others reaches the end having done both, and the drop that comes after a close does nothing.

Every other member checks the flag first, and none of them may skip it. fclose releases the handle, so the pointer the struct holds afterwards names storage C has freed; reaching it would be a use-after-free rather than a call that fails. What comes back instead is NotOpen, which is EBADF — the code the operating system reports for the same mistake made one layer down.

A read on a closed file latches rather than answering quietly empty. An empty read means end of input, and a program told that would conclude it had read the whole file when what it had done was close it too early. So got.len is 0 and failed() is true, and the two together are the truth.

A failure from close is a real one, incidentally: the flush it performs is where a full disk finally reports. A program that cares about its output checks the close and not only the writes.

Why a read came back empty

read hands back an empty slice for the end of the input and for a failure alike, and failed says only that something went wrong. read_failure says what: the same IoError — the system’s words and its errno — that a whole-file read answers for the same cause, or None while nothing has failed.

import sysl.fs.{IoError, open}
import sysl.io.Reader

var f = open("/tmp").unwrap()

print(f.read_failure().is_none())

var window: [8]u8
var got = f.read(window)

print(got.len, f.failed())

val why = f.read_failure().unwrap()

print(why.code(), why == IoError.IsADirectory)
print(f.read(window).len, f.read_failure().unwrap().code())
true
0 true
21 true
0 21

It is None before any read and after a clean read to the end, since the end of the input is not a failure. Once a read has failed the answer stays, and a later read that fails again replaces it with its own. Reading a file opened write-only reports what the system says (EBADF); reading a closed file reports NotOpen, while closing a file that had failed on nothing leaves it None. A failure that arrives after some bytes were already read is held back until those are handed out, so it shows here once the read that tells it has returned. failed is one latch for reads and writes, so a failed write is answered here as well.

Copies share one handle

A File is a struct and therefore a value, so passing one to a function makes a second File. It holds its state behind a &FileState rather than holding the pointer directly, and that is what makes close answerable at all: every copy shares one state, so closing either is closing the file, and closing it twice is harmless rather than a use-after-free. A value type holding the pointer would have made that mistake easy. It is also what gives the descriptor one point of death: the file is closed when the last copy goes, and stays open while any copy lives.

Locking a file

lock(kind) takes an advisory lock on the whole file and waits for it; try_lock(kind) takes it now or answers an IoError whose would_block() is true; unlock() gives it up. LockKind.Shared is the readers’ lock, any number of which may be held at once; LockKind.Exclusive is the writer’s, which nobody else may hold beside it, shared or exclusive.

import sysl.fs.{LockKind, create, open, remove_file}
import sysl.process.pid

val path = s"/tmp/sysl-fs-doc-lock-${pid()}"
var writer = create(path).unwrap()
var reader = open(path).unwrap()

writer.lock(LockKind.Exclusive).unwrap()

val refused = reader.try_lock(LockKind.Shared).unwrap_err()

print(refused.would_block(), refused.message())

writer.unlock().unwrap()
print(reader.try_lock(LockKind.Shared).is_ok(), writer.try_lock(LockKind.Shared).is_ok())
print(writer.try_lock(LockKind.Exclusive).unwrap_err().would_block())

writer.close().unwrap()
reader.close().unwrap()
remove_file(path).unwrap()
true Resource temporarily unavailable
true true
true

It is flock‘s lock, and it belongs to the open file — to the descriptor one open made, which every copy of the File shares — not to the process and not to the thread. That one sentence settles every question about who holds it:

a second open of the same path, in this processis somebody else: excluded exactly as another process is (above)
another processexcluded while the lock is held; a process that ends, or is killed, lets go of what it held
a copy of the Fileis the same open file, so it holds the same lock, and unlock through it releases it
a fiber that takes a lock and switches awaystill holds it: the lock is the file’s, not the stack’s, and the home side may unlock it
another threadcannot be handed a File at all (below); one that opens the file itself is another open file
closing another descriptor to the same filereleases nothing
close, the last copy going, unlockreleases it, after handing over what is buffered
into_raw_fdthe descriptor keeps the lock, and it goes when the caller closes that number

The row about closing another descriptor is the reason for the choice. POSIX’s other lock, fcntl‘s record lock, belongs to the process, so two opens in one program never exclude each other, and closing any descriptor to the file drops every lock the process holds on it — a library that opens the same file to read its size silently unlocks its caller’s database. Rust’s File::lock (1.89) is flock on Unix too.

import sysl.fs.{LockKind, create, open, remove_file}
import sysl.process.pid

val path = s"/tmp/sysl-fs-doc-lock2-${pid()}"
var held = create(path).unwrap()

held.lock(LockKind.Exclusive).unwrap()

var glance = open(path).unwrap()

glance.close().unwrap()

var other = open(path).unwrap()

print(other.try_lock(LockKind.Shared).unwrap_err().would_block())

other.close().unwrap()
held.close().unwrap()
remove_file(path).unwrap()
true

The rest of what it is:

  • Advisory. It binds only programs that ask for it; a read or a write from one that never locks is not stopped.
  • The mode the file was opened in does not matter. A file opened only for reading takes an Exclusive lock, which fcntl‘s write lock refuses.
  • Asking again converts. A file that holds a lock and asks for the other kind has it changed, and the change is not atomic: the old lock is let go of first, so another waiter may get in between, and a try_lock that fails part-way may leave the file holding nothing.
  • try_lock never waits, and what it refuses with is EWOULDBLOCK carried in Other — 35 on macOS and the BSDs, 11 on Linux — so a program asks would_block() rather than the number.
  • unlock hands over what is buffered before it lets go, as close does, so a reader waiting for the lock finds every byte the writer wrote under it. The lock is given up even where that fails, and the failure is what unlock answers.
  • Taking a lock drops what was read ahead. Bytes the file read before the lock were read while a writer may have been busy, so lock — and a try_lock that succeeds — moves the descriptor back to where the program thinks it is, and the next read reads them again under the lock. A file that had read to its end reads on past it. What is buffered for writing is left alone.
import sysl.fs.{LockKind, open, open_update, read_text, remove_file, write_text}
import sysl.io.Reader
import sysl.process.pid
import sysl.text.from_utf8

val path = s"/tmp/sysl-fs-doc-lock4-${pid()}"

write_text(path, "version 1").unwrap()

var reader = open(path).unwrap()
var first: [1]u8

print(from_utf8(reader.read(first)).unwrap())

var writer = open_update(path).unwrap()

writer.lock(LockKind.Exclusive).unwrap()
writer.write("VERSION 2".bytes)
writer.unlock().unwrap()
print(read_text(path).unwrap())

reader.lock(LockKind.Shared).unwrap()

var rest: [16]u8

print(from_utf8(reader.read(rest)).unwrap())

writer.close().unwrap()
reader.close().unwrap()
remove_file(path).unwrap()
v
VERSION 2
ERSION 2
  • lock waits, and is declared @blocks; so, through its flush, is unlock, since a write may wait for the device. try_lock does neither, so a @no_block path may try a lock and may not wait for one:
import sysl.fs.{File, LockKind}

@no_block
on_tick(f: File) -> bool = f.lock(LockKind.Shared).is_ok()

main()
    print(1)
this reaches 'sysl.fs.File.lock', which blocks through 'sysl.fs.sys.lock', and 'on_tick' declared '@no_block'

A File‘s shared state is counted without atomics, so a File does not cross to another thread; a thread that needs the lock opens the file itself and is, by the table, somebody else:

import sysl.fs.{File, LockKind, create}
import sysl.threads.spawn

struct Job
    f: File

work(j: *Job) -> unit
    _ = j.f.lock(LockKind.Shared)

main()
    val j: &Job = Job(create("/tmp/sysl-fs-doc-lock3").unwrap())

    _ = spawn(&work, &*j)
reaches a '&FileState', whose count is not

Where it is not. On Linux a file on NFS is locked with fcntl underneath (the kernel emulates flock there as a whole-file record lock, since 2.6.12), so there the lock meets fcntl‘s locks and an Exclusive one needs a file opened for writing; a filesystem with no lock service at all answers an error. wasi and Windows have no flock, and the hosted library answers not supported on this target there. A freestanding program answers the two hooks itself (below).

Mapping a file instead of reading it

struct Mapped
    len(self) -> usize
    is_empty(self) -> bool
    @views(self)
    bytes(&self) -> []const u8

map_file(path: string) -> Result[&Mapped, IoError]

A mapping is a file’s bytes made readable in place: the operating system hands back an address range and reads a page only when something touches it, so map_file costs a few calls whatever the size of the file, and a byte nobody looks at is never read. That is what a program opening files of many gigabytes — an editor, an index — wants instead of read_bytes. f.map() is the same for a file already open, handing over what it still has buffered first.

import sysl.fs.{map_file, write_text, remove_file, NotFound, IsADirectory}
import sysl.process.pid

var path = s"/tmp/sysl-fs-doc-map-${pid()}.txt"

write_text(path, "mapped, not read").unwrap()

count(path: string, b: u8) -> int
    val m = map_file(path).unwrap()
    var n = 0

    for x in m.bytes() do if x == b then n += 1

    remove_file(path).unwrap()
    print(m.len(), m.bytes()[0..<6].len)
    n

print(count(path, u8('e')))
print(map_file(path).unwrap_err() == NotFound, map_file("/tmp").unwrap_err() == IsADirectory)
16 6
2
true true

Four rules are in it.

It is read-only and private, so nothing can write the file through it. The writable kind is a different type, MappedMut from File.map_mut, below: a store into a shared mapping reaches the file with no Result to say it failed — a full disk is a signal, not an error — which is why it is asked for by name and flushed with a call that does answer.

It outlives the file and the name. The descriptor is closed before map_file answers, and the file removed above is still readable through m until m goes — which is what lets an editor that saves by renaming a new file over the old one keep reading the text it is undoing back to.

Dropping the last reference unmaps it, so it is a &Mapped, held like any type with a destructor. bytes() is a view borrowed from it: the compiler refuses a view that would outlive the mapping, so a view cannot be read after the unmap.

An empty file maps nothing. POSIX refuses a mapping of no bytes, so an empty file answers an empty Mapped with no call made. What a mapping cannot survive is the file being cut short underneath it: the pages past the new end have nothing behind them, and the operating system answers a read of one with a signal. A program mapping a file somebody else may truncate reads it instead.

Advising the system about a mapping

enum Advice
    Normal
    Random
    Sequential
    WillNeed
    DontNeed

struct Mapped
    advise(self, advice: Advice, from: usize = 0, len: usize = usize::Max) -> Result[unit, IoError]

page_size() -> usize

A program reading a huge file through once can tell the system it is done with the part behind it: m.advise(Advice.DontNeed, 0, done). from is rounded down to a page boundary (page_size()) and the end up, len left out means to the end of the mapping, and a range past the end is Other(22) (EINVAL). An empty mapping or an empty range does nothing and answers Ok. The advice never changes what bytes() reads: a dropped page is read back from the file if touched again.

import sysl.fs.{map_file, write_text, remove_file, Advice, page_size}
import sysl.process.pid

val path = s"/tmp/sysl-fs-doc-advise-${pid()}.txt"

write_text(path, "advised, not changed").unwrap()

val m = map_file(path).unwrap()

for a in [Advice.Sequential, Advice.WillNeed, Advice.DontNeed]
    m.advise(a, 3, 5).unwrap()

print(m.advise(Advice.Normal, 0, m.len() + 1).is_err(), page_size() >= 512)
print(m.bytes()[0..<7].len, m.bytes()[0])
remove_file(path).unwrap()
true true
7 97

It is a hint, and what the system does with it is its own. On Linux DontNeed drops a file mapping’s pages, which keeps the resident size small through a long scan; macOS ignores it for a file mapping, so the call succeeds and the pages stay. On a freestanding target a program that calls advise supplies sysl_fs_advise (a build that calls it without is refused, naming it), and sysl_fs_page_size if its pages are not 4096 bytes.

Durability, and a writable mapping

File.sync_data(*self) -> Result[unit, IoError]
File.full_sync(*self) -> Result[unit, IoError]
File.map_mut(*self, len: usize = usize::Max) -> Result[&MappedMut, IoError]
open_uncached(path: string, create: bool = false) -> Result[File, IoError]

struct MappedMut
    len(self) -> usize
    is_empty(self) -> bool
    @views(self)
    bytes(&self) -> []u8
    flush(self, from: usize = 0, len: usize = usize::Max) -> Result[unit, IoError]
    flush_async(self, from: usize = 0, len: usize = usize::Max) -> Result[unit, IoError]

What a database asks of its files. There are three strengths of “it is written”, and each hands over what the File still buffers first. sync is fsync. sync_data is the same without the metadata a reader does not need: fdatasync on Linux; on macOS, where there is nothing cheaper, plain fsync. full_sync is the one that survives a power cut: fcntl(F_FULLFSYNC) on macOS, which makes the drive empty its own write cache (plain fsync there stops at the drive), and fsync elsewhere, where it already is the full one. All three are NotOpen on a closed file.

open_uncached bypasses the page cache — O_DIRECT on Linux, fcntl(F_NOCACHE) on macOS — for a program with its own buffer pool. It opens for reading and writing, and create makes a missing file without emptying an existing one. It is used through read_at and write_at. Linux holds it to alignment: the buffer’s address, the offset and the length of each transfer are multiples of the device’s block size (use 4096), or the call is Other(22) (EINVAL); macOS has no such rule, and a program that wants to run on both aligns for Linux.

map_mut is a shared, writable mapping: a store through bytes() is a store to the file. The file must be open for update (a read-only one is PermissionDenied). The mapping is never longer than the file, since a page past the end is a signal when touched rather than an error, so a len above the file’s size is Other(22); a program that wants more truncates first. flush writes a range back and returns when it is there (msync(MS_SYNC)), flush_async only schedules it, and a range past the mapping is Other(22). flush puts the bytes in the file, not on the device: follow it with sync_data or full_sync where a power cut matters.

import sysl.fs.{File, create_update, open_update, open, read_text, remove_file, PermissionDenied}
import sysl.process.pid

var path = s"/tmp/sysl-fs-doc-dur-${pid()}.txt"
var f = create_update(path).unwrap()

f.write("0123456789".bytes)
f.sync_data().unwrap()
f.full_sync().unwrap()
f.close().unwrap()

put(f: File)
    val m = f.map_mut().unwrap()
    val v = m.bytes()

    v[0] = u8('X')
    v[9] = u8('Z')
    m.flush().unwrap()
end put

var g = open_update(path).unwrap()

put(g)
g.close().unwrap()
print(read_text(path).unwrap())

var ro = open(path).unwrap()

print(ro.map_mut().unwrap_err() == PermissionDenied)
ro.close().unwrap()
remove_file(path).unwrap()
X12345678Z
true

The path tier

import sysl.fs.{write_text, exists, is_file, is_dir, readable, writable, rename, remove_file, size_of}
import sysl.process.pid

var a = s"/tmp/sysl-fs-doc-6a-${pid()}.txt"
var b = s"/tmp/sysl-fs-doc-6b-${pid()}.txt"

write_text(a, "x").unwrap()

print(exists(a), is_file(a), is_dir(a), readable(a), writable(a))
print(is_dir("/tmp"), is_file("/tmp"))

rename(a, b).unwrap()

print(exists(a), exists(b), size_of(b).unwrap())

remove_file(b).unwrap()

print(exists(b), remove_file(b).unwrap_err())
true true false true true
true false
false true 1
false no such file or directory

A path holding a zero byte is refused, with Other(22) (EINVAL), by every call that takes one — before C is asked, because C reads a path up to its first zero and the call would act on a different file than the one named (open("a\0b") would open a). Only the bytes of the path count, so a slice that ends before a zero is a fine path. exists, is_file and is_dir answer false for it.

import sysl.fs.{metadata, exists}

val p = "/tmp\0zzz"

print(metadata(p).unwrap_err())
print(exists(p), exists(p[0..<4]))
Invalid argument
false true

exists answers false for a path that exists under a directory the program may not search, which is the one way it differs from the question it looks like it is asking. That case cannot be told from absence without a second call whose answer would already be stale — and every caller that matters, one about to open the file, gets the truth from the open.

is_dir and is_file ask stat, following a symbolic link. A directory the program may not read is still a directory, and is_file means a regular file: a directory, a device, a socket or a FIFO answers false, as does a missing or dangling path. On a target whose stat hook is unsupported, is_dir asks whether the path opens as a directory and is_file whether something is there that does not.

remove_file refuses a directory rather than removing it. It is unlink, where C’s own remove quietly does either; two names for two intentions is what lets a program that meant one of them find out it had the other. remove_dir is rmdir and needs the directory empty, reporting DirectoryNotEmpty — the one code in the whole set whose number the two platforms disagree about, which is why it is read through a call rather than written as a literal.

rename replaces whatever was at the destination, is one operation as far as anything watching is concerned when both paths are on the same filesystem, and fails rather than copying when they are not. That is rename(2)‘s contract and worth knowing, since a program moving a file across devices has to read and write it itself.

rename_no_replace moves a path only where nothing is at the destination, and reports AlreadyExists where anything is — a file, a directory, a dangling link, and the moved file itself by the same path or a hard link, where rename succeeds doing nothing — leaving both names as they were. The check and the move are one step in the kernel: renamex_np with RENAME_EXCL on macOS, renameat2 with RENAME_NOREPLACE on Linux. exists followed by rename is a race that replaces whatever appears between the two, so a target with neither call answers not supported on this target rather than that, and a Linux filesystem that cannot make the promise answers Other(22) (EINVAL).

import sysl.fs.{read_text, remove_file, rename_no_replace, write_text}
import sysl.process.pid

val a = s"/tmp/sysl-fs-doc-rn-a-${pid()}.txt"
val b = s"/tmp/sysl-fs-doc-rn-b-${pid()}.txt"
val c = s"/tmp/sysl-fs-doc-rn-c-${pid()}.txt"

write_text(a, "from").unwrap()
write_text(b, "to").unwrap()

print(rename_no_replace(a, b).unwrap_err(), read_text(b).unwrap())

rename_no_replace(a, c).unwrap()

print(read_text(c).unwrap())

remove_file(b).unwrap()
remove_file(c).unwrap()
already exists to
from

make_dir makes one directory and needs its parent to be there. It asks for 0o777, letting the process umask narrow it: asking for less would override the environment’s decision rather than defer to it. make_dir_all is the one every caller actually wants — it climbs with sysl.path.parent and makes each level from the topmost missing one down, and a directory that is already there is success rather than AlreadyExists, because the question being asked is make sure this is there. It tries the path first and climbs only on NotFound, so a file standing above the leaf (x/y with x a file) is NotADirectory, and a file at the leaf itself (x) is AlreadyExists.

remove_dir_all is its opposite and is a post-order walk, because rmdir refuses a directory that is not empty. A symbolic link is unlinked rather than followed, which is what keeps it from deleting something outside the tree it was pointed at, and a path that is not there at all is success — a caller tearing down after a failure should not have to know how far the failure got.

remove_dir_all needs one thing make_dir_all does not: to know whether an entry is a symbolic link without following it, and the only reading that answers that is link_metadata — the stat hook asked not to follow. Following the link instead would delete things nobody asked it to, which is the property the walk exists to have, so a target whose stat hook answers UNSUPPORTED gets not supported on this target back rather than a removal that guessed.

import sysl.fs.{make_dir_all, remove_dir_all, write_text, exists, is_dir}
import sysl.path.join
import sysl.process.pid

var dir = s"/tmp/sysl-fs-doc-tree-${pid()}"

remove_dir_all(dir).unwrap()
make_dir_all(join(dir, "a/b/c")).unwrap()
write_text(join(dir, "a/b/note.txt"), "hi").unwrap()

print(is_dir(join(dir, "a/b/c")))

make_dir_all(join(dir, "a/b")).unwrap()          // already there, and that is success

remove_dir_all(dir).unwrap()

print(exists(dir))
true
false

One reading of an entry

metadata is the stat this module was written around not having, and it answers everything one call knows: the size, the mode, how many names lead to the entry, its owner and group, its inode and device, and three Instants. One call rather than several is the point — asking separately whether a path is a directory, how big it is and when it changed is three trips into the kernel and three chances for the answer to be about three different files.

import sysl.fs.{write_text, metadata, set_permissions, remove_file, Kind}
import sysl.process.pid

var path = s"/tmp/sysl-fs-doc-meta-${pid()}.txt"

write_text(path, "0123456789").unwrap()
set_permissions(path, 0o644).unwrap()

var m = metadata(path).unwrap()

print(m.size, m.kind(), m.is_file(), m.is_dir())
print(m.permissions() == 0o644, m.links >= 1, m.modified.us > 0)

remove_file(path).unwrap()
10 file true false
true true true

A file can be born with its permission bits. create, append and create_update take a mode, 0o666 by default (as do the whole-file writers and a Dir‘s own create, append, create_update, write_bytes and write_text), which goes to open(2) with O_CREAT and so is narrowed by the process umask as in POSIX. A secret file asks 0o600 and is owner-only from the moment it exists; creating it and then calling set_permissions leaves a window in which it is open to group and others. The mode applies only when the file is created: create_update or append on a file that exists keeps the mode it has. Bits above the twelve permission bits are dropped, as set_permissions drops them. File.set_permissions(mode) is fchmod on the open descriptor, for a program that holds the file and wants its mode changed without trusting the path; a closed file answers NotOpen. On a target with no permission bits the mode given at creation is ignored and File.set_permissions answers “not supported on this target”, as set_permissions does.

import sysl.fs.{create, metadata, remove_file}
import sysl.process.pid

var path = s"/tmp/sysl-fs-doc-mode-${pid()}.txt"

var f = create(path, 0o600).unwrap()

print(metadata(path).unwrap().permissions() == 0o600)

f.set_permissions(0o640).unwrap()

print(metadata(path).unwrap().permissions() == 0o640)

f.close().unwrap()
remove_file(path).unwrap()
true
true

link_metadata is the same reading about the path itself — so a symbolic link is described rather than followed, and it is the only call here that can report one. metadata, is_dir and exists all follow a link silently, which is the right default and was for a long time the only behaviour available.

Meta.same_file is the inode and the device together, which is what says two paths name one file. Neither identifies a file on its own: inode numbers are reused, and are unique only within a device.

Whether something is a program is asked two ways, and they answer different questions. Meta.executable() reads the bits: a regular file with any of its three execute bits set, whoever is asking — so a directory, whose execute bits mean it may be searched, answers false, as does a link that link_metadata described. executable(path) asks the system, beside readable and writable and as POSIX’s access with X_OK does: whether this program may run it, which a file whose only execute bit is another class’s is not. A program acting as user 0 may run a file with any execute bit set.

import sysl.fs.{write_text, metadata, set_permissions, executable, remove_file}
import sysl.process.pid

val path = s"/tmp/sysl-fs-doc-exec-${pid()}.sh"

write_text(path, "#!/bin/sh\necho hi\n").unwrap()
set_permissions(path, 0o755).unwrap()
print(metadata(path).unwrap().executable(), executable(path))

set_permissions(path, 0o644).unwrap()
print(metadata(path).unwrap().executable(), executable(path))

print(metadata("/tmp").unwrap().executable(), executable("/tmp"))

remove_file(path).unwrap()
true true
false false
false true

Who owns it

Meta.owner and Meta.group are u32s, the type sysl.process.user() answers, so “is this file mine” is one comparison with nothing converted on either side. set_owner(path, owner, group) is the writing half, beside set_permissions and over one chown: it sets both, and a program changing only one passes unchanged for the other, the 4294967295 that chown(2) reads as “leave this id as it is”.

import sysl.fs.{write_text, metadata, set_owner, remove_file, unchanged}
import sysl.process.{pid, user}

val path = s"/tmp/sysl-fs-doc-owner-${pid()}.txt"

write_text(path, "mine").unwrap()

val m = metadata(path).unwrap()

print(m.owner == user())

set_owner(path, m.owner, m.group).unwrap()
print(metadata(path).unwrap().owner == m.owner)

set_owner(path, unchanged, m.group).unwrap()
print(metadata(path).unwrap().owner == m.owner)

set_owner(path, unchanged, unchanged).unwrap()
print(unchanged == 4294967295)

remove_file(path).unwrap()
true
true
true
true

Giving a file away is privileged, as chown(2) makes it: a program not acting as user 0 that hands one to somebody else is refused with NotPermitted. Giving a file to the owner and group it already has is the one change anybody may make. A symbolic link is followed, as set_permissions follows one. A target whose filesystem has no owners answers not supported on this target.

set_link_owner(path, owner, group) is the same change to the path itself, over one lchown: a symbolic link is given the ids and what it names keeps its own, the writing half of link_metadata‘s reading. Anything else at the path is changed exactly as set_owner changes it, under the same privilege rule. So a link the program made to a file of root’s is the program’s to set, and the file is not:

import sysl.fs.{symlink, link_metadata, metadata, set_owner, set_link_owner, remove_file, IoError}
import sysl.process.{pid, user}

val link = s"/tmp/sysl-fs-doc-lchown-${pid()}"

symlink("/bin/sh", link).unwrap()

val mine = link_metadata(link).unwrap()

print(set_link_owner(link, mine.owner, mine.group).is_ok())
print(metadata(link).unwrap().owner == 0)
print(user() == 0 || set_owner(link, mine.owner, mine.group).unwrap_err() == IoError.NotPermitted)

remove_file(link).unwrap()
true
true
true

The names behind the ids are sysl.process‘s, beside user() and group(): user_name and group_name, and user_id and group_id the other way.

set_modified(path, when) sets the modification time of a file or a directory, and its access time with it, over one utimensat hook. It is how a program records that something was used without writing to it: a cache that evicts the least recently used entry touches what it hands out. A path that is not there is NotFound; the filesystem keeps the time to its own resolution, so a reading may round what was set.

import sysl.fs.{write_text, metadata, set_modified, remove_file}
import sysl.process.pid
import sysl.time.Instant

val path = s"/tmp/sysl-fs-doc-modified-${pid()}.txt"

write_text(path, "x").unwrap()
set_modified(path, Instant(1500000000000000)).unwrap()
print(metadata(path).unwrap().modified.us / 1000000)

remove_file(path).unwrap()
1500000000

Its times, one at a time, and when it was made

set_times(path, accessed, modified) sets the two times apart, each an Option[Instant]: None leaves that time exactly as it was (UTIME_OMIT), which is what a program copying a file’s times needs when it carries one and not the other. set_times(p, Some(t), Some(t)) is set_modified(p, t). link_set_times is the same on the path itself, utimensat‘s AT_SYMLINK_NOFOLLOW: a symbolic link’s own times are set, link_metadata reads them back, and the file it names is untouched — so a copy of a tree can carry its links’ times as well as its files’.

import sysl.fs.{write_text, symlink, metadata, link_metadata, set_times, link_set_times, make_dir,
                remove_dir_all}
import sysl.process.pid
import sysl.time.Instant

val dir = s"/tmp/sysl-fs-doc-times-${pid()}"
val file = dir + "/file"
val link = dir + "/link"

make_dir(dir).unwrap()
write_text(file, "x").unwrap()
symlink(file, link).unwrap()

set_times(file, Some(Instant(1500000000123456)), Some(Instant(1400000000654321))).unwrap()
set_times(file, None, Some(Instant(1300000000000001))).unwrap()

val m = metadata(file).unwrap()

print(f"${m.accessed.us} ${m.modified.us}")

link_set_times(link, Some(Instant(1000000000000000)), Some(Instant(1000000000000000))).unwrap()
print(link_metadata(link).unwrap().modified.us)
print(metadata(file).unwrap().modified.us)

remove_dir_all(dir).unwrap()
1500000000123456 1300000000000001
1000000000000000
1300000000000001

A time is an Instant, kept to the microsecond, which APFS, ext4, btrfs and xfs all keep exactly. There is no “now by the kernel’s clock” (UTIME_NOW), because an Instant is a time rather than an instruction: Some(sysl.time.now()) sets one by this program’s clock. A path that is not there is NotFound from either call, also where both times are None — that changes nothing, but still asks that the path be there, so the answer is the same on every platform (Linux’s utimensat would otherwise succeed on nothing). The third time, changed, is nobody’s to set.

Meta.created is the birth time, an Option[Instant]: Some where the platform and the filesystem keep one, and None where they do not, rather than a date nobody recorded. macOS answers it from st_birthtimespec on APFS and HFS+; Linux answers it from statx‘s STATX_BTIME where the kernel (4.11), the C library (glibc 2.28, musl 1.2.5, Bionic API 30) and the filesystem all know it; a program supplying sysl.fs.sys itself answers it where its stat hook fills it in. Nothing sets it — though on macOS, a modification time set earlier than the birth time pulls the birth time back to it, a file not having changed before it existed.

import sysl.fs.{write_text, metadata, remove_file}
import sysl.process.pid
import sysl.time.now

val path = s"/tmp/sysl-fs-doc-created-${pid()}.txt"

write_text(path, "x").unwrap()

// Known on this machine or not, a birth time is never one in the future.
print(metadata(path).unwrap().created match
    Some(t) -> t.us <= now().us + 1000000
    None -> true)

remove_file(path).unwrap()
true

How much room a filesystem has

space(path) is one statvfs of the filesystem holding path, as a Space of three byte counts: total, free, and available — the part of free a program not acting as user 0 may take, since a filesystem may hold a reserve back for root. So available <= free <= total always, and available is the one to compare a write against. Each is a block count times the fragment size, f_frsize, which is the unit POSIX says the counts are in. path may name a file or a directory anywhere on the filesystem; a path that is not there is NotFound.

import sysl.fs.space

val s = space("/tmp").unwrap()

print(s.total > 0, s.available <= s.free, s.free <= s.total)
true true true

It is a reading, not a reservation: another program can take the room before the next write lands, so a program that must not run out still handles the write’s own NoSpaceLeft.

import sysl.fs.{write_text, symlink, read_link, is_link, hard_link, metadata,
                canonicalize, make_dir_all, remove_dir_all}
import sysl.path.{join, file_name}
import sysl.process.pid

var dir = s"/tmp/sysl-fs-doc-links-${pid()}"

remove_dir_all(dir).unwrap()
make_dir_all(dir).unwrap()
write_text(join(dir, "target"), "hello").unwrap()

symlink("target", join(dir, "here")).unwrap()

print(read_link(join(dir, "here")).unwrap())
print(is_link(join(dir, "here")), is_link(join(dir, "target")))
print(metadata(join(dir, "here")).unwrap().size)

hard_link(join(dir, "target"), join(dir, "second")).unwrap()

print(metadata(join(dir, "target")).unwrap().links)
print(file_name(canonicalize(join(dir, "here")).unwrap()))

remove_dir_all(dir).unwrap()
target
true false
5
2
Some(target)

A symbolic link’s target is stored as written, which is what makes a tree of relative links movable — and a link is allowed to point at nothing, which is sometimes the point. A hard link is a second name for one file: the two are equal afterwards, there is no original, and the file goes when the last of them does, which is what Meta.links counts.

canonicalize follows every link and answers an absolute path. It is sysl.path.normalize‘s counterpart and not its equivalent: where a/b is a link, the two answer different files, and confusing them is the shape of every path-traversal bug there is. Reach for this one whenever the answer decides access to something.

Extended attributes

get_xattr(path: string, name: string) -> Result[[]u8, IoError]
set_xattr(path: string, name: string, value: []const u8) -> Result[unit, IoError]
remove_xattr(path: string, name: string) -> Result[unit, IoError]
list_xattrs(path: string) -> Result[Buf[string], IoError]

link_get_xattr(path: string, name: string) -> Result[[]u8, IoError]
link_set_xattr(path: string, name: string, value: []const u8) -> Result[unit, IoError]
link_remove_xattr(path: string, name: string) -> Result[unit, IoError]
link_list_xattrs(path: string) -> Result[Buf[string], IoError]

An extended attribute is a named value a filesystem keeps beside a file’s contents: a download’s quarantine mark, a backup tool’s checksum, a security label. A name is text and a value is bytes: a value may hold any byte, a zero among them, and may be empty, and it is passed with its length, never terminated. An attribute that is not there is NoAttribute, so “no such attribute” is not mistaken for “no such file”, which stays NotFound:

import sysl.fs.{write_text, get_xattr, set_xattr, remove_xattr, list_xattrs, make_dir_all,
                remove_dir_all, NoAttribute}
import sysl.process.pid

val dir = s"/tmp/sysl-fs-doc-xattr-${pid()}"
val f = dir + "/notes"

remove_dir_all(dir).unwrap()
make_dir_all(dir).unwrap()
write_text(f, "hello").unwrap()

val value: []u8 = [104, 0, 105]

set_xattr(f, "user.sysl.tag", value).unwrap()

val back = get_xattr(f, "user.sysl.tag").unwrap()

print(back.len, back[0], back[1], back[2])
print(list_xattrs(f).unwrap().any((n) -> n == "user.sysl.tag"))

remove_xattr(f, "user.sysl.tag").unwrap()

print(get_xattr(f, "user.sysl.tag").unwrap_err() == NoAttribute)
print(get_xattr(dir + "/gone", "user.sysl.tag").unwrap_err())

remove_dir_all(dir).unwrap()
3 104 0 105
true
true
no such file or directory

Every call comes in two, like metadata and link_metadata. The plain one follows a symbolic link and asks about what it points at; the link_ one asks about the link itself, which is the platform’s XATTR_NOFOLLOW on macOS and its l-prefixed calls on Linux. macOS keeps attributes on a link apart from its target’s; Linux refuses a user. attribute on a link with NotPermitted.

A name is what the platform says it is. Linux wants a namespace before a dot (user., trusted., security.) and refuses a bare name with Other(95), EOPNOTSUPP; macOS takes any name, by convention reverse-DNS. A name holding a zero byte is refused with Other(22), EINVAL, before anything is asked, since C would read it as the shorter name before the zero. A filesystem that keeps no attributes answers its own refusal — ENOTSUP, or EPERM on a device node.

list_xattrs answers what this process may see, in the filesystem’s order. That is neither sorted nor everything: Linux leaves out a trusted. attribute for an unprivileged process, and macOS puts names of its own on files it has seen (com.apple.provenance), so a program asks for the names it set rather than counting. A name that is not UTF-8 makes the call answer InvalidUtf8, as entries does.

A value is asked for twice — its size, then its bytes — and one that grew in between is asked for again rather than handed back cut short.

Where the program is, and somewhere to put things

current_dir and set_current_dir are the working directory. Both are process-wide, which is the thing to know before reaching for the second: a library that changes it changes it for every thread and every other library in the program. Prefer building an absolute path.

copy_file is a read-and-write loop rather than a platform fast path, which is a decision: copyfile(3) and copy_file_range(2) have different names, different signatures and different failure modes, and what is here is correct everywhere. It does not carry the permission bits over — a caller that wants them reads metadata(from).permissions() and writes it with set_permissions, which says out loud that it is doing so.

truncate cuts a file to a length, or extends it to one with zeroes, and makes nothing: a path that is not there reports NotFound. File.truncate is the same on an open file, and does not move the position — which is what makes it usable in the middle of writing.

Temporary files and directories

temp_root() is where temporary things go: TMPDIR where it is set and not empty; otherwise, on macOS, the per-user directory confstr(_CS_DARWIN_USER_TEMP_DIR) names (/var/folders/…/T, the one NSTemporaryDirectory answers, which only this user can write in); otherwise /tmp. Trailing slashes are dropped — macOS’s own TMPDIR ends in one — so a name joined to it with one / is the path the system reports back. It is read afresh at every call and is not checked: a root that is not there is the failure of the call that tries to make something in it.

temp_dir(prefix) makes a directory nobody else can take, mode 0700, and temp_file(prefix) makes a file nobody else can take, mode 0600, answered open for reading and writing with its path. Each name is the prefix (empty by default) and six characters chosen to make it unique. Both are created rather than named, which is the whole point: inventing a path and then making it leaves a gap in which somebody else can take the name on a shared /tmp — and for a file, plant a link there for create to follow. The file is made with O_CREAT | O_EXCL in the same step that opens it, as mkstemp does; the umask can narrow either mode and never widens it. make_temp_dir is temp_dir under its first name.

import sysl.fs.{metadata, read_text, remove_dir_all, remove_file, temp_dir, temp_file, temp_root}
import sysl.path.{file_name, parent}

val d = temp_dir("sysl-fs-doc-").unwrap()
defer remove_dir_all(d).unwrap()

var (f, p) = temp_file("sysl-fs-doc-").unwrap()
defer remove_file(p).unwrap()

f.write("draft".bytes)
f.close().unwrap()

print(parent(d).unwrap() == temp_root(), parent(p).unwrap() == temp_root())
print(file_name(p).unwrap().len, metadata(d).unwrap().permissions() == 0o700,
      metadata(p).unwrap().permissions() == 0o600)
print(read_text(p).unwrap())
true true
18 true true
draft

Nothing removes them but the caller, and defer is the idiom, as above: nothing in this module runs at the end of a scope that the scope did not say, so neither answer is a guard that deletes on drop. The File closes when its last copy goes, like any other; the file it was open on stays. A root that is not there answers NotFound, one this process may not write in PermissionDenied, one that is a file NotADirectory, and a prefix that makes the name too long for the system the platform’s ENAMETOOLONG as an Other. A prefix holding a / or a NUL is refused with Other(22), EINVAL, before anything is made: it would name something other than one entry of the root. A root whose name is not UTF-8 makes a path no string can hold: the two calls take back what they made and answer InvalidUtf8, and temp_root answers /tmp for it.

Where a directory belongs

A different question from where the program is: not where it happens to be, but where the machine’s own conventions say a file of a given kind goes. Four calls, each answering Option[string].

import sysl.fs.{home_dir, cache_dir, config_dir, data_dir}

print(home_dir().is_some())
print(cache_dir().is_some(), config_dir().is_some(), data_dir().is_some())

print(cache_dir().unwrap() != home_dir().unwrap())
true
true true true
true
callmacOSWindowselsewhere
home_dir$HOME%USERPROFILE%$HOME
cache_dir~/Library/Caches%LOCALAPPDATA%$XDG_CACHE_HOME, or ~/.cache
config_dir~/Library/Application Support%APPDATA%$XDG_CONFIG_HOME, or ~/.config
data_dir~/Library/Application Support%APPDATA%$XDG_DATA_HOME, or ~/.local/share

They are Option because a machine may genuinely not say. An environment with no HOME set is not a failure with an errno behind it; it is a machine that has not told the program where its user lives. A caller that gets None falls back to something of its own knowingly, which is the whole difference between this and reading the variable itself. A variable set to nothing counts as unset here, which is where these differ from sysl.env‘s get: an empty string is a truthful reading of an environment and is not a place.

They name a directory and do not make one. Nothing here touches the filesystem — the answer is a path, and whether it exists is exists and whether it should is make_dir_all. A question that created a directory as a side effect could not be asked by a program that was about to read.

A program appends its own name, and nothing here does it for you. These say where the machine keeps caches, not where yours goes:

import sysl.fs.cache_dir
import sysl.path.join

val mine = cache_dir().map((d) -> join(d, "myprogram"))

print(mine.is_some())
true

A library that guessed the leaf would be guessing the program’s identity, which is not its to guess.

macOS answers the same directory for config_dir and data_dir, and that is Apple’s convention rather than a gap here. The platform draws the line between cache and everything else and does not draw one between configuration and data. Inventing a ~/Library/Config to make the four look symmetrical would put files where nothing else on the machine looks.

Listing a directory

import sysl.fs.{entries, make_dir, write_text, remove_file, remove_dir}
import sysl.process.pid

var dir = s"/tmp/sysl-fs-doc-entries-${pid()}"

remove_dir(dir)          // in case an earlier run of this page left it behind
make_dir(dir).unwrap()
write_text(dir + "/one.txt", "a").unwrap()
write_text(dir + "/two.txt", "b").unwrap()

var names = entries(dir).unwrap()

print(names.len())
print(names[0] == "one.txt" || names[0] == "two.txt")

remove_file(dir + "/one.txt").unwrap()
remove_file(dir + "/two.txt").unwrap()
remove_dir(dir).unwrap()

print(entries(dir).unwrap_err())
2
true
no such file or directory

. and .. are left out, because every caller drops them: a program listing a directory is asking what is in it, and a recursive walk that forgets the filter does not terminate. The order is the filesystem’s — not sorted, and not stable between two listings of one directory. A program that wants an order applies one.

A name that is not UTF-8 makes the whole listing answer InvalidUtf8, the offset counted within that name. POSIX names are bytes — Linux stores any of them, though macOS’s APFS refuses to create one — so this is reachable rather than theoretical. The whole call fails rather than the name being skipped, because a listing with a name silently missing is a wrong answer that looks like a right one: a copy that leaves a file behind, a clean-up that leaves it in place. entry_bytes is the listing for a directory whose names need not be text — every name as the bytes the filesystem holds, the same .-and-.. rule, never InvalidUtf8:

import sysl.fs.{entry_bytes, make_temp_dir, remove_dir_all, write_text}
import sysl.path.join
import sysl.text.from_utf8

val dir = make_temp_dir("sysl-fs-doc-bytes").unwrap()

write_text(join(dir, "only"), "x").unwrap()

for name in entry_bytes(dir).unwrap().view()
    print(name.len, from_utf8(name).unwrap_or("?"))

remove_dir_all(dir).unwrap()
4 only

A listing is three hooks — open, next name, close — and the next name arrives as bytes and a length. readdir hands back a struct dirent whose name field sits at an offset the platforms disagree about, which is the transcription the module refuses; the hosted answer reads it in a shim beside it, where the header decides the layout, and nothing in sysl learns it.

Walking a tree

entries lists one directory. walk reports a whole tree — the root first, then everything under it — and is a cursor, so a for walks it:

import sysl.fs.{make_dir_all, remove_dir_all, walk, write_text}
import sysl.process.pid

var dir = s"/tmp/sysl-fs-doc-walk-${pid()}"

remove_dir_all(dir).unwrap()
make_dir_all(dir + "/a/b").unwrap()
write_text(dir + "/a/b/deep", "x").unwrap()

var files = 0
var dirs = 0

for item in walk(dir)
    val e = item.unwrap()

    if e.is_dir() then dirs += 1 else files += 1

print(dirs, files)

remove_dir_all(dir).unwrap()
3 1

Each item is a Result, and that is the error policy being left to you: ? in the body makes the first unreadable directory fatal, and ignoring it makes the walk best effort. A directory that cannot be read is one Err and the walk carries on with what is left.

An entry another process removes while the walk is under way is absent, not an error. A directory is listed once and its entries are looked at afterwards, so a lock directory or a temporary file may be gone by the time the walk reaches it. Such an entry is skipped, and a directory removed after it was reported is walked as an empty one. A root that is not there when the walk starts is still an Err.

A symbolic link is reported and never followed. is_dir follows a link, so a walk that classified with it would descend into a link to a directory without ever deciding to — and a link pointing at one of its own ancestors would make the walk unbounded. Each entry carries a link_metadata reading, so e.is_link() is what a caller asks.

bottom_up() reverses the order — a directory after everything under it, which is what remove_dir_all needs since rmdir refuses a directory that is not empty. skip_dir() prunes the directory just reported, and it needs the cursor by hand rather than a for, since a for walks a copy:

var w = walk(root)

loop
    val e = w.next() match
        None -> break
        Some(item) -> item?

    if e.is_dir() && hidden(e.path) then w.skip_dir()

Filtering a walk by a glob

walk(root).matching(pattern) reports only the entries whose path matches a glob, which is what a build tool, a test runner and a --exclude flag all want and what every caller was otherwise writing by hand:

import sysl.fs.{make_dir_all, remove_dir_all, walk, write_text}
import sysl.path.relative_to
import sysl.process.pid

var dir = s"/tmp/sysl-fs-doc-matching-${pid()}"

remove_dir_all(dir).unwrap()
make_dir_all(dir + "/src/deep").unwrap()
make_dir_all(dir + "/.git").unwrap()
write_text(dir + "/notes.md", "x").unwrap()
write_text(dir + "/src/mid.sysl", "x").unwrap()
write_text(dir + "/src/deep/low.sysl", "x").unwrap()
write_text(dir + "/.git/config", "x").unwrap()

var found: [8]string
var n = 0

for item in walk(dir).matching("**/*.sysl")
    found[n] = relative_to(item.unwrap().path, dir).unwrap()
    n += 1

print(n)

remove_dir_all(dir).unwrap()
2

The pattern is matched against the path relative to the root, which is what makes a pattern portable between one caller walking . and another walking /home/ed/project. The .git tree is absent because a leading . is hidden from every wildcard, and notes.md because it is not a .sysl file.

The root itself never matches. Its relative path is ".", which no pattern here matches — and that is the answer a caller wants: a walk filtered by *.sysl is asking for files rather than for the directory it started in.

It filters and does not prune. Every directory is still descended into, because a directory whose own name does not match may hold a file whose path does — which is the whole point of a pattern with a separator in it. A caller that wants whole subtrees skipped wants skip_dir, which is a decision about where to go rather than about what to report, and the two compose: drive the walk by hand, prune what you do not want to enter, and ask matches yourself.

An Err passes through unfiltered, since a directory that could not be read is not an entry with a path to test, and losing it would turn a permission failure into an empty result.

Copying a tree

copy_dir_all is the walk with a leaf action, and remove_dir_all is the same walk asked the other way round:

import sysl.fs.{copy_dir_all, make_dir_all, read_text, remove_dir_all, write_text}
import sysl.process.pid

var dir = s"/tmp/sysl-fs-doc-copy-${pid()}"

remove_dir_all(dir).unwrap()
make_dir_all(dir + "/from/inner").unwrap()
write_text(dir + "/from/inner/one", "hello").unwrap()

copy_dir_all(dir + "/from", dir + "/to").unwrap()

print(read_text(dir + "/to/inner/one").unwrap())

remove_dir_all(dir).unwrap()
hello

A directory is merged into and a file is never overwritten — the safe half of each question. A destination that already holds a subtree gains what this brings; one that already holds a file of a name being copied reports AlreadyExists rather than quietly replacing something.

Permissions are carried, which is where this differs from copy_file: an executable copied with that one stops being executable. A symbolic link is copied as a link, pointing wherever it pointed.

A failure part way through leaves what it has already written. Nothing removes a tree on the way out, because it cannot know whether the destination existed before it started, and deleting one you owned would be far worse than the failure being reported. A caller needing the destination to appear whole or not at all copies into make_temp_dir and renames the result into place, which is the only way to get atomicity from a filesystem.

Confined to one directory

open_dir holds a directory open, and the Dir it answers reaches what is beneath it and nothing else. It is what a sandbox is built on: a script given one directory reads and writes through it, and no symbolic link and no .. leads it out. Its calls are the module’s own, with the path relative to the directory — open, create, append, open_update, create_update, open_with, link_metadata, exists, remove_file, make_dir, remove_dir, rename and rename_no_replace, and the whole-file read_bytes, read_text, write_bytes and write_text, which answer exactly what the module-level functions of those names answer (a failed write carries the OS’s reason) and refuse an escape, an absolute path or a link exactly as open does:

import sysl.fs.{open_dir, make_dir_all, remove_dir_all, write_text, read_text}
import sysl.process.pid

var dir = s"/tmp/sysl-fs-doc-beneath-${pid()}"

remove_dir_all(dir).unwrap()
make_dir_all(dir + "/granted/notes").unwrap()

val granted = open_dir(dir + "/granted").unwrap()
var f = granted.create("notes/today").unwrap()

f.write("written beneath".bytes)
f.close().unwrap()

print(read_text(dir + "/granted/notes/today").unwrap())
print(granted.link_metadata("notes/today").unwrap().size, granted.exists("notes/today"))

granted.write_text("notes/plain", "whole file")

print(granted.read_text("notes/plain").unwrap())

granted.remove_file("notes/today").unwrap()

print(granted.exists("notes/today"))

remove_dir_all(dir).unwrap()
written beneath
15 true
whole file
false

A symbolic link at any component is refused: the last one or one above it, and one pointing back inside as firmly as one pointing out. So is every absolute path, and every .. that would climb above the directory (.., a/../..). Each refusal is an IoError that refused_link() or escaped() recognises, and everything else fails as it always does:

import sysl.fs.{open_dir, make_dir_all, remove_dir_all, write_text, symlink}
import sysl.process.pid

var dir = s"/tmp/sysl-fs-doc-refused-${pid()}"

remove_dir_all(dir).unwrap()
make_dir_all(dir + "/granted").unwrap()
write_text(dir + "/secret", "not yours").unwrap()
symlink(dir + "/secret", dir + "/granted/door").unwrap()

val granted = open_dir(dir + "/granted").unwrap()

for name in ["door", "../secret", dir + "/secret", "nothing"]
    granted.open(name) match
        Ok(_) -> print(s"$name: opened")
        Err(e) -> print(s"${e.refused_link()} ${e.escaped()} $e")

remove_dir_all(dir).unwrap()
true false the path goes through a symbolic link
false true the path leads out of its directory
false true the path leads out of its directory
false false no such file or directory

The kernel does the refusing, in the call that opens, because a check made first and an open made after it is a race a swapped link wins: openat2 with RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS on Linux, openat with O_NOFOLLOW_ANY (and O_RESOLVE_BENEATH where the SDK has it) on macOS. The absolute path and the climbing .. are refused before the call as well, so that the error says why. A platform that cannot confine a path reports unsupported() rather than opening one it did not confine.

A .. that stays inside is accepted, by lexical collapse. Before the kernel is asked, every path — both paths of a rename — has its . components dropped and each x/.. removed, so a/b/../c is a/c. That is sound only because links stay refused: with no link anywhere, a/b/.. can only mean a, and the kernel never walks b, so nothing can be swapped under the path. The one difference from asking the kernel is that a/missing/../c reaches a/c instead of failing with NotFound. A path ending in . or .. must still name a directory; a path with neither is handed on exactly as written. A path that collapses to nothing (., a/..) names the directory itself: link_metadata and exists describe it, make_dir answers AlreadyExists, and open and open_with asking only to read hand back a read-only handle on the directory (an open asking to write or create gets the kernel’s answer for a directory, IsADirectory). The calls that need a name beneath it — remove_file, remove_dir, either path of a rename — refuse it with an error names_itself() recognises:

import sysl.fs.{open_dir, make_dir_all, remove_dir_all, read_text}
import sysl.process.pid

var dir = s"/tmp/sysl-fs-doc-collapse-${pid()}"

remove_dir_all(dir).unwrap()
make_dir_all(dir + "/granted/notes").unwrap()

val granted = open_dir(dir + "/granted").unwrap()

granted.write_text("notes/../top", "collapsed").unwrap()
print(read_text(dir + "/granted/top").unwrap())

for name in ["notes/..", "notes/../..", "missing/../top"]
    granted.remove_dir(name) match
        Ok(_) -> print(s"$name: removed")
        Err(e) -> print(s"$name: ${e.names_itself()} ${e.escaped()} $e")

print(granted.open("notes/..").is_ok(), granted.link_metadata("missing/../top").unwrap().size)

remove_dir_all(dir).unwrap()
collapsed
notes/..: true false the path names the directory itself
notes/../..: false true the path leads out of its directory
missing/../top: false false not a directory
true 9

make_dir, remove_dir, rename and rename_no_replace act as their module-level namesakes do, with both paths of a rename beneath the one directory. Each opens the directory holding its last component beneath the Dir, refusing a link or an escape on the way, and makes its call there on that component alone: mkdirat, unlinkat with AT_REMOVEDIR, renameat, and for rename_no_replace renameatx_np with RENAME_EXCL on macOS and renameat2 with RENAME_NOREPLACE on Linux. A link as a last component is never followed: make_dir finds something there, remove_dir finds no directory, and a rename moves or replaces the link itself. open_with takes the module’s OpenOptions, and no option loosens the confinement — an option only adds to what the open asks, and the refusal of every link and escape is added beneath it whatever was asked:

import sysl.fs.{open_dir, open_options, make_dir_all, remove_dir_all, read_text}
import sysl.process.pid

var dir = s"/tmp/sysl-fs-doc-beneath-moves-${pid()}"

remove_dir_all(dir).unwrap()
make_dir_all(dir + "/granted").unwrap()

val granted = open_dir(dir + "/granted").unwrap()
var f = granted.open_with("draft", open_options().write().create_new()).unwrap()

f.write("first".bytes)
f.close().unwrap()

val again = granted.open_with("draft", open_options().write().create_new()).unwrap_err()

print(s"$again")

granted.make_dir("kept").unwrap()
granted.write_text("kept/final", "older").unwrap()

val kept = granted.rename_no_replace("draft", "kept/final").unwrap_err()

print(s"$kept")

granted.rename("draft", "kept/final").unwrap()

print(read_text(dir + "/granted/kept/final").unwrap())

val full = granted.remove_dir("kept").unwrap_err()

print(s"$full")
print(granted.rename("kept/final", "../outside").unwrap_err().escaped())

remove_dir_all(dir).unwrap()
already exists
already exists
first
directory not empty
true

link_metadata describes a link as the last component instead of following it, and remove_file there removes the link and never what it names; a link above the last component is refused by both. open_dir itself refuses a link as the directory’s own last component, and follows the components above it, which are the caller’s own path. A File opened through a Dir is a descriptor of its own and outlives it; the Dir‘s descriptor is closed when its last reference goes.

Answering the filesystem on a freestanding target

Everything above reaches the filesystem through sysl.fs.sys and through nothing else: one extern per call — sysl_fs_open, _read, _write, _pread, _pwrite, _sync, _close, _seek, _fstat, _ftruncate, _map, _unmap, _advise and _page_size (the last two asked only by a program that advises a mapping; _page_size answers usize, zero meaning 4096; _sync_data, _full_sync, _map_shared and _msync asked only by a program that calls sync_data, full_sync, map_mut or a flush; _lock, which may wait, asked only by File.lock, and _lock_now, which may not, by try_lock and unlock, both taking how as sysl.fs.sys‘s lock_shared, lock_exclusive or lock_release; and the open flags carry an uncached bit and, from open_with, an exclusive, a sync, a dsync and a nofollow bit), _stat, _truncate, _mkdir, _rmdir, _unlink, _rename, _rename_no_replace (asked only by a program that calls rename_no_replace), _access, _chmod, _fchmod (asked only by a program that calls File.set_permissions), _chown, _lchown and _space (asked only by a program that calls set_link_owner or space), _opendir, _readdir, _closedir, _getcwd, _chdir, _temp_root, _temp_dir, _temp_file, _symlink, _link, _readlink and _realpath, and for a Dir _dir_open, _open_beneath, _stat_beneath, _unlink_beneath, _mkdir_beneath, _rmdir_beneath, _rename_beneath and _rename_no_replace_beneath (asked only by a program that calls Dir.rename_no_replace), which refuse a link with ELOOP and an escape with EXDEV, and for the extended attributes _getxattr, _setxattr, _removexattr and _listxattr, each taking a follow flag (non-zero follows a link) and the two that answer bytes asked first with no room for the size they would take, then with room for the bytes, answering -34, ERANGE, where it grew in between. Each answers an int by the contract every *.sys module has (sysl.io.sys, sysl.process.sys, sysl.net.sys and sysl.env.sys too): zero or more is success, a negative answer is the code() of the IoError it failed with, negated as a system call answers it (so -1 is EPERM and comes back as NotPermitted, where -13, EACCES, is PermissionDenied), and the one status UNSUPPORTED means the target cannot make that call at all. UNSUPPORTED is a constant in sysl.sys, -38 on every platform and deliberately not the host’s ENOSYS, which hosted suppliers translate into it. A path crosses as a pointer and a length, with no terminator; what a call produces besides its status it writes through a pointer it was handed.

On a hosted target the library answers them itself, over the C library, under weak exports (a module may supply another module’s extern). A freestanding target has no operating system, so a program there answers each hook it reaches with an @export of its own — even where the manifest grants it a C library (libc): newlib’s open and read are stubs the board answers, not a filesystem.

@export("sysl_fs_open")
k_open(path: *u8, len: usize, flags: u32, mode: u32, fd: *int) -> int = -38

A hook the program reaches and leaves unanswered is refused when it is compiled, all of them in one sentence, rather than surfacing at the link as a symbol no line of the program names:

error: this program reaches 'sysl.fs', and 'aarch64-freestanding' has no operating system under it for
the standard library to answer a filesystem with, so the program answers it: define 'sysl_fs_close',
'sysl_fs_open', 'sysl_fs_read', 'sysl_fs_write' with '@export', each taking what its 'extern' in
'sysl.fs.sys' declares and answering zero or the code of an 'IoError' negated

The question is asked only of what the program reaches, so a freestanding program that never touches a file is asked nothing.

Every call on this page is there for such a program, the reading ones included: metadata, link_metadata, set_permissions, set_owner, set_link_owner, set_modified, set_times, link_set_times and space are one stat, chmod, chown, lchown, utimensat, set_times or statvfs hook, executable is the access hook readable and writable are, the walk and remove_dir_all, copy_dir_all and publish_dir are entries and link_metadata with a leaf action, and temp_root, temp_dir and canonicalize are the temp_root, temp_dir and realpath hooks (temp_dir asks rmdir too, and temp_file its own hook with unlink, for a root no string can name), and temp_root answers /tmp where its hook fails. A supplier fills Stat‘s sixteen numbers in POSIX’s shape and leaves zero what it has nothing to say about — a birth time it does not know is three zeros, which reads as created == None; a hook it answers UNSUPPORTED comes back from these calls as not supported on this target. The one exception is the permission step of copy_dir_all: a target whose chmod answers UNSUPPORTED has no permission bits, so there is nothing to carry and the copy goes on; any other error from it still fails the copy.

What is absent, and why

Anything stat would answer used to be, and it is not any more: metadata is that call, and the struct stat it comes back in stays in the hosted answer’s shim, where the header decides the layout, with sixteen numbers — sysl.fs.sys.Stat — crossing rather than a transcription. That is the shape this section always prescribed, arrived at the day something needed it.

The rule the whole module is written under is one sentence: a question that can be answered by a call whose signature is all there is to get right is answered here, and one that cannot is answered by C. No C structure is transcribed into sysl. Three headers are included, in the shims behind entries, metadata and size — a question C can answer in a few lines is answered by C, and one that would need a structure transcribed into sysl is still not answered at all. Where that leaves a gap, an extern of one’s own — or a .c of one’s own — is the honest way across it, and foreign functions is where that is written up.

Lexical path handling is absent from this module on purpose, and is sysl.path. This one requires os and a requirement is module-wide, so one getcwd beside join would take the whole of path handling away from every program that has no operating system to ask.

Argument types

import sysl.fs.write_text

write_text("/tmp/sysl-fs-doc-x.txt", 42)
'text' of 'sysl.fs.write_text' is string, but int was given
import sysl.fs.write_bytes

write_bytes("/tmp/sysl-fs-doc-x.txt", "text")
'bytes' of 'sysl.fs.write_bytes' is []const u8, but string was given

write_bytes wants bytes and s.bytes is how a string supplies them — free, since a string already is a validated []u8. write_text is the same call with that step written in.

And every one of these answers with a Result, which has to be opened before the file inside it is:

import sysl.fs.open

var f = open("/tmp/sysl-fs-doc-x.txt")

f.close()
type 'Result' has no method 'close'

? inside a function that returns a Result, or unwrap() in a program that would rather stop, are the two ways through. Errors and contracts has the rest.


Next: sysl.math — the float functions, and the integer traits.

Search

Esc
↑↓ to navigate ↵ to open Esc to close