Skip to content
Kavachकवच

Files: Details and permissions

● Intermediate3 minBefore this: Files

fs.info gives a file's kind, size, time of change and permissions; fs.set_read_only and fs.set_permissions change them.

use std.fs

fn main() ! FsError uses Fs, Console {
    try fs.write_text("deploy.sh", "echo hi\n")
    const info = try fs.info("deploy.sh")
    print("{info.kind}, {info.size} bytes, read-only {info.read_only}")

    try fs.set_read_only("deploy.sh", true)
    print("read-only {(try fs.info("deploy.sh")).read_only}")

    try fs.set_permissions("deploy.sh", 0o644)    // the owner may write it again
    print("read-only {(try fs.info("deploy.sh")).read_only}")

    fs.set_permissions("deploy.sh", 0o10000) catch e => print("{e}")
    try fs.remove("deploy.sh")
}

The program ran and printed:

kavach run info.kav

File, 8 bytes, read-only falseread-only trueread-only falseFailed(path: "deploy.sh", reason: "permissions are 0o0 to 0o7777")
info.kav: Kavach code, then what running it prints
pub type FileKind = File | Folder | Link

pub type FileInfo {
    pub kind: FileKind
    pub size: Int          // in bytes; 0 for a folder
    pub modified_ms: Int   // when it last changed: a moment (14.4)
    pub read_only: Bool    // the owner may not write it
    pub permissions: Int   // the Unix bits, such as 0o644
}
std.fs: Kavach code
  • permissions are the Unix bits, written in octal: 0o644 lets the owner read and write, and everyone else read; 0o755 lets anyone run the file.
  • A mode outside 0o0 to 0o7777 fails, as the last line shows.
  • On Windows, files have no Unix bits. permissions is 0o444 for a read-only file and 0o666 otherwise (0o555 and 0o777 for a folder), as Go and Rust report them. set_permissions keeps only the owner's write bit, 0o200. A drive that keeps no Unix bits, such as a Windows drive mounted in Linux, keeps only read-only too.
  • fs.info reads, so it needs Fs.read; the others change files and need Fs.write.