1// The file system: directories, paths and what is at them.2//3// File contents are std::io's (File, read_file, write_file); this module4// lists, makes, removes and renames, reads metadata, and maps files into5// memory (MappedFile). Paths are UTF-86// bytes with `'/'` between parts, which every system takes; on Windows `'\'`7// too (PathStyle). The externs are the runtime's (alloyc/src/support/8// system.c, system_windows.c), which the interpreter reaches9// as well.1011import std::option;12import std::vector;13import std::string;14import std::io;15import std::sort;16import std::dispose;17import std::process;18import std::ffi;1920extern al_sys_dir_open(path: c_string) -> i64;21extern al_sys_dir_next(dir: i64, buffer: &var [u8], capacity: u64) -> i64;22extern al_sys_dir_close(dir: i64);23extern al_sys_path_info(path: c_string, out: &var [u64]) -> i32;24extern al_sys_make_directory(path: c_string) -> i32;25extern al_sys_remove_directory(path: c_string) -> i32;26extern al_sys_remove_file(path: c_string) -> i32;27extern al_sys_rename(from: c_string, target: c_string) -> i32;28extern al_sys_user_directory(which: UserDirectory, buffer: &var [u8], capacity: u64) -> i64;29extern al_sys_map_file(path: c_string, length: &var [u64]) -> c_pointer;30extern al_sys_unmap_file(address: c_pointer, length: u64);3132/* --- What is at a path --- */3334exp type Kind = enum {35 File,36 Directory,37 Other // a device, a socket, a pipe38};3940exp type Metadata = struct {41 exp kind: Kind,42 exp size: u64, // in bytes43 exp modified: i64 // the last change, in nanoseconds since 197044};4546// What is at the path, following links, or `None` when nothing is.47exp fn metadata(path: &[u8]) -> Option<Metadata> {48 var out: [u64 : 3] = [0, 0, 0];49 const terminated = move null_terminated(&path);50 if (al_sys_path_info(&terminated, &var out[..]) != 0) {51 return ::None;52 }53 const kind = match (out[0]) {54 1 Kind::File;55 2 Kind::Directory;56 else Kind::Other;57 };58 return ::Some(Metadata { .kind = kind, .size = out[1], .modified = out[2] as i64 });59}6061exp fn exists(path: &[u8]) -> bool {62 return metadata(&path) is ::Some;63}6465exp fn is_file(path: &[u8]) -> bool {66 return match (metadata(&path)) {67 ::Some |m| m.kind is ::File;68 ::None false;69 };70}7172exp fn is_directory(path: &[u8]) -> bool {73 return match (metadata(&path)) {74 ::Some |m| m.kind is ::Directory;75 ::None false;76 };77}7879/* --- Directories --- */8081// The names in the directory, `'.'` and `..` left out, sorted bytewise; or82// `None` when it cannot be read.83exp fn list_directory(path: &[u8]) -> Option<Vector<String>> {84 const terminated = move null_terminated(&path);85 const dir = al_sys_dir_open(&terminated);86 if (dir == 0) {87 return ::None;88 }89 var names = Vector<String>::empty();90 var buffer: *var [u8] = new [0 : 1024]; // a Windows name may take 765 bytes in UTF-891 while (true) {92 const length = al_sys_dir_next(dir, &var buffer, buffer.length());93 if (length < 0) {94 break;95 }96 if (length as u64 > buffer.length()) {97 continue; // longer than any name the system allows98 }99 names.push(String::from(&buffer[..length as u64]));100 }101 al_sys_dir_close(dir);102 sort_by(&var names.items(), (a, b) => bytes_before(&a.view(), &b.view()));103 return ::Some(move names);104}105106// Makes the directory, whose parent must exist; false when it cannot.107exp fn make_directory(path: &[u8]) -> bool {108 const terminated = move null_terminated(&path);109 return al_sys_make_directory(&terminated) == 0;110}111112// Makes the directory and any missing above it; true when it exists113// afterwards.114exp fn make_directories(path: &[u8]) -> bool {115 if (is_directory(&path)) {116 return true;117 }118 const above = &parent(&path);119 if (above.length() > 0 && above.length() < path.length() && !make_directories(&above)) {120 return false;121 }122 return make_directory(&path) || is_directory(&path);123}124125// Removes the directory, which must be empty; false when it cannot.126exp fn remove_directory(path: &[u8]) -> bool {127 const terminated = move null_terminated(&path);128 return al_sys_remove_directory(&terminated) == 0;129}130131/* --- Files --- */132133exp fn remove_file(path: &[u8]) -> bool {134 const terminated = move null_terminated(&path);135 return al_sys_remove_file(&terminated) == 0;136}137138// Moves the file or directory, replacing a file at the target; false when139// it cannot (across file systems among other cases).140exp fn rename(from: &[u8], target: &[u8]) -> bool {141 const from_terminated = move null_terminated(&from);142 const target_terminated = move null_terminated(&target);143 return al_sys_rename(&from_terminated, &target_terminated) == 0;144}145146// Copies the file's bytes to the target, replacing it; false when either147// cannot be opened or a write fails.148exp fn copy_file(from: &[u8], target: &[u8]) -> bool {149 var source = if (File::open(&from) is ::Some |move f|) move f else {150 return false;151 };152 defer source.dispose();153 var out = if (File::create(&target) is ::Some |move f|) move f else {154 return false;155 };156 defer out.dispose();157 var buffer: *var [u8] = new [0 : 65536];158 while (true) {159 const read = source.read(&var buffer);160 if (read == 0) {161 return true;162 }163 if (!out.write(&buffer[..read])) {164 return false;165 }166 }167}168169/* --- Mapped files --- */170171// A file's bytes mapped read-only into the program's memory: the system172// reads its pages from the disk as they are first touched and may drop173// them again when short of memory, so a large file read in a few places,174// such as a font, costs only what is read. Where nothing is mapped (on175// the web, under WASI, in `alloyc run`, for an empty file or one that is176// not regular) it is read whole, as `read_file` does. Disposing it177// unmaps it, after which no view of it may be read. The file must not178// shrink while it is mapped.179//180// ```alloy181// import std::io;182//183// write_file(&"mapped.txt", &"mapped bytes");184// var file = if (MappedFile::open(&"mapped.txt") is ::Some |move f|) move f else {185// panic "the file was written";186// };187// expect_equal(&file.view(), &"mapped bytes");188// file.dispose();189// remove_file(&"mapped.txt");190// ```191exp type MappedFile : Disposable = struct {192 kept: KeptMappedFile,193};194195// The file at the path mapped, or read whole where it cannot be; None196// when it cannot be read.197exp fn MappedFile::open(path: &[u8]) -> Option<MappedFile> {198 if (KeptMappedFile::open(&path) is ::Some |move kept|) {199 return ::Some(MappedFile { .kept = move kept });200 }201 return ::None;202}203204// The file's bytes.205exp fn view(self file: &MappedFile) -> &[u8] {206 return &file.kept.view();207}208209// Whether the system maps the file, false where it was read whole.210exp fn is_mapped(self file: &MappedFile) -> bool => file.kept.is_mapped();211212// Unmaps the file.213exp fn dispose(self file: &var MappedFile) {214 if (file.kept.address != 0) {215 al_sys_unmap_file(file.kept.address, file.kept.length);216 }217 file.kept = KeptMappedFile { .address = 0, .length = 0, .read = new [0 : 0] };218}219220// A file mapped as `MappedFile` is, for a holder that cannot be disposed:221// it stays mapped until the program ends, as a library loaded does, so222// its views never dangle. For files a program reads as long as it runs.223exp type KeptMappedFile = struct {224 address: c_pointer, // the system's mapping, 0 where the file was read whole225 length: u64,226 read: *[u8], // the file read whole227};228229// As `MappedFile::open`.230exp fn KeptMappedFile::open(path: &[u8]) -> Option<KeptMappedFile> {231 const terminated = move null_terminated(&path);232 var length: [u64 : 1] = [0];233 const address = al_sys_map_file(&terminated, &var length[..]);234 if (address != 0) {235 return ::Some(KeptMappedFile {236 .address = address,237 .length = length[0],238 .read = new [0 : 0]239 });240 }241 if (read_file(&path) is ::Some |move bytes|) {242 return ::Some(KeptMappedFile {243 .address = 0,244 .length = bytes.length(),245 .read = move bytes246 });247 }248 return ::None;249}250251exp fn view(self file: &KeptMappedFile) -> &[u8] {252 if (file.address != 0) {253 return &file.address.view<u8>(file.length);254 }255 return &file.read[..];256}257258exp fn is_mapped(self file: &KeptMappedFile) -> bool => file.address != 0;259260/* --- Where apps keep their files --- */261262// The directory the app keeps its data in, the user's directory for apps'263// data joined with the app's name (the user's directory itself for ""):264// `$XDG_DATA_HOME/<app>` on Linux, `~/.local/share/<app>` when that is265// not set to an absolute path, `%APPDATA%\<app>` on Windows,266// `~/Library/Application Support/<app>` on macOS. Under WASI it is the267// same as Linux's when the runtime gives the variable and the directory268// is preopened; None there otherwise, and on the web, which keeps data in269// the browser (std::storage). It may not exist yet.270exp fn data_directory(app: &[u8]) -> Option<String> {271 return user_directory(UserDirectory::Data, &app);272}273274// The directory the app keeps what it can make again in, which the275// system may clear: `$XDG_CACHE_HOME/<app>` (else `~/.cache/<app>`),276// `%LOCALAPPDATA%\<app>`, `~/Library/Caches/<app>`; as `data_directory`277// otherwise.278exp fn cache_directory(app: &[u8]) -> Option<String> {279 return user_directory(UserDirectory::Cache, &app);280}281282// Which directory al_sys_user_directory gives.283type UserDirectory = enum : i32 {284 Data = 0,285 Cache = 1286};287288fn user_directory(which: UserDirectory, app: &[u8]) -> Option<String> {289 if (target() == "web-wasm32") {290 return ::None;291 }292 var buffer: *var [u8] = new [0 : 1024];293 var length = al_sys_user_directory(which, &var buffer, buffer.length());294 if (length > buffer.length() as i64) {295 buffer = new [0 : length to u64];296 length = al_sys_user_directory(which, &var buffer, buffer.length());297 }298 if (length <= 0 || length > buffer.length() as i64) {299 return ::None;300 }301 return ::Some(join(&buffer[..length to u64], &app));302}303304/* --- Paths --- */305306// How paths are written: Linux's, `'/'` between parts and a leading `'/'` for307// the root, or Windows', `'\'` or `'/'` between parts and a root that may hold308// a drive ("C:\", "C:" alone relative to that drive's directory) or a309// share ("\\server\share\"). The functions below follow the target's310// style; the `_in` ones take it, for paths of another system.311exp type PathStyle = enum {312 Unix,313 Windows314};315316// The style of the target the program is built for.317exp fn native_style() -> PathStyle {318 if (target() == "windows-x86_64") {319 return PathStyle::Windows;320 }321 return PathStyle::Unix;322}323324// The two joined with one separator between them; the part alone when it325// has a root of its own, the base alone when the part is empty.326exp fn join(base: &[u8], part: &[u8]) -> String {327 return join_in(native_style(), &base, &part);328}329330// The path up to its last part: "a/b" for "a/b/c", "/" for "/c", "" for331// "c", the root for the root. Trailing separators are not a part.332exp fn parent(path: &[u8]) -> &[u8] {333 return &parent_in(native_style(), &path);334}335336// The last part: "c.txt" for "a/b/c.txt", "" for a root.337exp fn file_name(path: &[u8]) -> &[u8] {338 return &file_name_in(native_style(), &path);339}340341// The last part without its extension: "c" for "a/c.txt", ".profile" for342// ".profile".343exp fn stem(path: &[u8]) -> &[u8] {344 return &stem_in(native_style(), &path);345}346347// The extension without its dot: "txt" for "a/c.txt", "" for "a/c" and348// ".profile".349exp fn extension(path: &[u8]) -> &[u8] {350 return &extension_in(native_style(), &path);351}352353exp fn join_in(style: PathStyle, base: &[u8], part: &[u8]) -> String {354 if (base.length() == 0 || root_length(style, &part) > 0) {355 return String::from(&part);356 }357 var out = String::from(&base);358 if (part.length() > 0) {359 const last = base[base.length() - 1];360 const drive_only = style is ::Windows361 && root_length(style, &base) == base.length()362 && last == ':';363 if (!is_separator(style, last) && !drive_only) {364 out.push(if (style is ::Windows) '\\' else '/');365 }366 out.append(&part);367 }368 return move out;369}370371exp fn parent_in(style: PathStyle, path: &[u8]) -> &[u8] {372 const root = root_length(style, &path);373 var k = trimmed_end(style, &path, root);374 while (k > root && !is_separator(style, path[k - 1])) {375 k -= 1;376 }377 if (k <= root) {378 return &path[..root];379 }380 var cut = k - 1;381 while (cut > root && is_separator(style, path[cut - 1])) {382 cut -= 1;383 }384 return &path[..cut];385}386387exp fn file_name_in(style: PathStyle, path: &[u8]) -> &[u8] {388 const root = root_length(style, &path);389 const end = trimmed_end(style, &path, root);390 var k = end;391 while (k > root && !is_separator(style, path[k - 1])) {392 k -= 1;393 }394 return &path[k..end];395}396397exp fn stem_in(style: PathStyle, path: &[u8]) -> &[u8] {398 const name = &file_name_in(style, &path);399 if (dot_of(&name) is ::Some |dot|) {400 return &name[..dot];401 }402 return &name;403}404405exp fn extension_in(style: PathStyle, path: &[u8]) -> &[u8] {406 const name = &file_name_in(style, &path);407 if (dot_of(&name) is ::Some |dot|) {408 return &name[dot + 1..];409 }410 return &name[..0];411}412413fn is_separator(style: PathStyle, byte: u8) -> bool {414 return byte == '/' || style is ::Windows && byte == '\\';415}416417// How long the path's root is: 0 for a relative path; on Unix 1 for a418// leading `'/'`; on Windows the drive ("C:", "C:\"), the share419// ("\\server\share\") or a leading separator.420fn root_length(style: PathStyle, path: &[u8]) -> u64 {421 if (style is ::Unix) {422 return if (path.length() > 0 && path[0] == '/') 1 else 0;423 }424 if (path.length() >= 2 && path[1] == ':' && is_letter(path[0])) {425 return if (path.length() > 2 && is_separator(style, path[2])) 3 else 2;426 }427 if (path.length() >= 2 && is_separator(style, path[0]) && is_separator(style, path[1])) {428 // the server, then the share, each ending at a separator429 var k: u64 = 2;430 for ([..2]) {431 while (k < path.length() && !is_separator(style, path[k])) {432 k += 1;433 }434 if (k < path.length()) {435 k += 1;436 }437 }438 return k;439 }440 return if (path.length() > 0 && is_separator(style, path[0])) 1 else 0;441}442443fn is_letter(byte: u8) -> bool {444 return byte >= 'a' && byte <= 'z' || byte >= 'A' && byte <= 'Z';445}446447// The last `'.'` of a name, unless it starts the name.448fn dot_of(name: &[u8]) -> Option<u64> {449 var k = name.length();450 while (k > 1) {451 k -= 1;452 if (name[k] == '.') {453 return ::Some(k);454 }455 }456 return ::None;457}458459// Where the path ends without trailing separators, its root kept.460fn trimmed_end(style: PathStyle, path: &[u8], root: u64) -> u64 {461 var end = path.length();462 while (end > root && end > 1 && is_separator(style, path[end - 1])) {463 end -= 1;464 }465 return end;466}467468fn bytes_before(a: &[u8], b: &[u8]) -> bool {469 const shorter = if (a.length() < b.length()) a.length() else b.length();470 for ([..shorter]) |k| {471 if (a[k] != b[k]) {472 return a[k] < b[k];473 }474 }475 return a.length() < b.length();476}477478fn null_terminated(path: &[u8]) -> *var [u8] {479 var terminated: *var [u8] = new [0 : path.length() + 1];480 terminated[..path.length()] = path[..];481 return move terminated;482}