Repository navigation
Expand file tree
/
Copy pathmodule.ae
More file actions
1454 lines (1352 loc) · 60.6 KB
/
Copy pathmodule.ae
File metadata and controls
1454 lines (1352 loc) · 60.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// std.fs - File System Module
// Import with: import std.fs
//
// Note: fs is otherwise extern-only (no std.string import) to stay a thin
// syscall layer. find_ext is the exception — it produces a string result and
// accumulates it with std.strbuilder (leak-free across the C walk callback).
//
// Provides file, directory, path, glob, and copy/move/realpath/chmod
// operations.
//
// API shape:
// - Raw externs end in `_raw` and return ptr/int in the old C-style
// convention. They are the escape hatch for advanced callers.
// - Aether-native wrappers (below) use Go-style `(value, err)` tuple
// returns and are the idiomatic way to call fs operations.
// - The newer wrappers `copy`, `move`, `realpath`, `chmod` ship the
// structured-error pilot from issue #392 — they return
// `(value, kind, message)` so callers can switch on the `KIND_*`
// enum below without parsing English. The pilot sits *next to*
// the (value, err) shape, not in place of it; every existing
// wrapper keeps its (value, err) or string-error return.
//
// Performance: `copy` zero-copies via the OS's best primitive
// (copy_file_range / sendfile / fcopyfile / CopyFileExW); falls back
// to an 8 MiB read/write loop on filesystems that reject the kernel
// primitives. `move` is rename(2) with transparent EXDEV →
// copy + unlink fallback. See aether_fs.c for the full hierarchy.
import std.strbuilder
exports(
file_open_raw, file_close_raw, file_read_all_raw, file_write_raw,
file_exists, file_delete_raw, file_size_raw, file_mtime,
dir_exists, dir_create_raw, dir_delete_raw, dir_list_raw,
fs_mkdir_p_raw,
fs_symlink_raw, fs_hard_link_raw, fs_readlink_raw, fs_is_symlink, fs_is_socket, fs_unlink_raw,
fs_make_temp_dir_raw, fs_make_temp_file_raw,
make_temp_dir, make_temp_file,
STAT_KIND_FILE, STAT_KIND_DIR, STAT_KIND_SYMLINK, STAT_KIND_OTHER,
STAT_KIND_SOCKET, STAT_KIND_FIFO, STAT_KIND_DEVICE,
WALK_CONTINUE, WALK_SKIP_SUBTREE, WALK_STOP,
fs_rename_raw,
fs_try_stat, fs_get_stat_kind, fs_get_stat_size, fs_get_stat_mtime,
fs_try_statvfs, fs_get_statvfs_total, fs_get_statvfs_free, fs_get_statvfs_avail,
statvfs,
fs_try_mounts, fs_get_mount_count,
fs_release_mounts,
mounts, mount_source, mount_point, mount_fstype, mount_options,
fs_try_block_info, fs_get_block_size_bytes, fs_get_block_removable,
fs_get_block_transport, block_info,
fs_try_read_binary, fs_get_read_binary, fs_get_read_binary_length,
fs_release_read_binary, fs_read_binary_tuple,
dir_list_count, dir_list_get, dir_list_kind, dir_list_free,
path_join, path_dirname, path_basename, path_extension, path_is_absolute,
path_separator,
clean, is_within_base, rel, join_clean, first_element,
fs_pread_raw, fs_pread_into_raw, fs_get_pread, fs_get_pread_length,
fs_release_pread, fs_ftruncate_raw, fs_fsync_raw,
pwrite, pread, pread_into, ftruncate, fsync,
file_fd_raw, fd,
fs_glob_raw, fs_glob_multi_raw,
fs_walk_raw, fs_watch_open_raw,
open, close, read_all, read, write, delete, size, mtime, exists,
create_dir, create_dir_with_mode, delete_dir, mkdir_p,
symlink, hard_link, readlink, unlink,
list_dir, glob, glob_multi,
walk, watch_open, watch_wait, watch_close,
write_binary, write_atomic, rename, file_stat, read_binary,
fs_copy_raw, fs_move_raw, fs_realpath_raw, fs_chmod_raw,
copy, move, realpath, chmod,
copy_tree, remove_tree,
find_ext, find_ext_excluding,
KIND_OK, KIND_NOT_FOUND, KIND_PERMISSION_DENIED, KIND_EXISTS,
KIND_CROSS_DEVICE, KIND_IO, KIND_INVALID, KIND_LOOP,
KIND_NAME_TOO_LONG, KIND_NO_SPACE, KIND_IS_DIR, KIND_NOT_DIR,
KIND_UNAVAILABLE,
last_os_error, fs_error_message
)
// ---- Structured-error kinds (pilot — issue #392) ----
// Returned as the second element of the (value, kind, message) tuple
// from `copy`, `move`, `realpath`, and `chmod`. Switch on these to
// programmatically discriminate between common failure modes without
// parsing the human-readable message. Non-fs callers should treat
// any non-zero kind as "an error happened" — the message remains the
// authoritative human-readable diagnostic.
//
// Values are stable; new kinds may be appended (always with a fresh
// integer above the existing range) but existing values are part of
// the surface contract. Mirror these in std/fs/aether_fs.h as
// AETHER_FS_KIND_* macros so the C side and the Aether surface
// remain in lock-step.
const KIND_OK = 0
const KIND_NOT_FOUND = 1 // ENOENT — path or component missing
const KIND_PERMISSION_DENIED = 2 // EACCES, EPERM
const KIND_EXISTS = 3 // EEXIST — destination already there (when caller asked not to overwrite)
const KIND_CROSS_DEVICE = 4 // EXDEV — rename across filesystems (move falls back transparently)
const KIND_IO = 5 // EIO and other partial-I/O failures
const KIND_INVALID = 6 // EINVAL — illegal argument (e.g. src == dst)
const KIND_LOOP = 7 // ELOOP — symlink cycle on realpath
const KIND_NAME_TOO_LONG = 8 // ENAMETOOLONG
const KIND_NO_SPACE = 9 // ENOSPC — disk full
const KIND_IS_DIR = 10 // EISDIR — operation on a directory where a regular file was required (or vice-versa for copy/move src)
const KIND_NOT_DIR = 11 // ENOTDIR — component of path is not a directory
const KIND_UNAVAILABLE = 99 // platform feature compiled out (reserved for follow-up modules; fs primitives never return this)
// File operations - raw externs
extern file_open_raw(path: string, mode: string) -> ptr
extern file_close_raw(file: ptr) -> int
extern file_read_all_raw(file: ptr) -> string @heap
extern file_write_raw(file: ptr, data: string, length: int) -> int
extern file_exists(path: string) -> int
// Path-agnostic existence check: 1 if anything is at `path`
// (regular file, directory, symlink, fifo, ...), 0 otherwise.
// Distinct from `file_exists` (regular-file-only) and
// `dir_exists` (directory-only). Use this when the caller doesn't
// care what kind of thing is there — only whether the path is bound.
// Matches POSIX `test -e`.
extern fs_path_exists(path: string) -> int
extern file_delete_raw(path: string) -> int
// Size in bytes, as `long` (#1021): the old int surface wrapped files
// >= 2 GiB to a negative value. Returns -1 on stat failure.
extern file_size_raw(path: string) -> long
// Get file modification time as a Unix timestamp. Infallible — returns
// 0 for missing files, null paths, or stat failure. Kept as a raw
// extern with no Go-style wrapper because callers already use the 0
// sentinel for "no mtime". `long` since #1021 (Y2038-safe).
extern file_mtime(path: string) -> long
// `file_mtime_raw` returns the file's mtime as Unix epoch seconds, or
// -1 if stat failed. Use this rather than `file_mtime` when you need
// to distinguish "1970-01-01 epoch file" from "stat failed" — the
// older `file_mtime` collapses both into 0. The `fs.mtime` wrapper
// below builds the standard (value, err) tuple on top of it.
extern file_mtime_raw(path: string) -> long
// Directory operations - raw externs
extern dir_exists(path: string) -> int
extern dir_create_raw(path: string) -> int
extern dir_create_mode_raw(path: string, mode: int) -> int
extern dir_delete_raw(path: string) -> int
extern dir_list_raw(path: string) -> ptr
// `mkdir -p` semantics: create `path` and any missing parent directories.
// Treats already-existing directories as success. Raw extern — use the
// `mkdir_p` wrapper below in most code.
extern fs_mkdir_p_raw(path: string) -> int
// Symbolic-link operations (raw externs). POSIX symlink(2) / readlink(2) /
// lstat(2); on Windows CreateSymbolicLinkW, the link's own reparse data
// and the directory entry's reparse tag.
// fs_symlink_raw: create a symlink at `link_path` pointing to `target`.
// `target` is recorded verbatim (relative stays relative);
// Windows stores its separators as backslashes.
// fs_readlink_raw: read a symlink's target (on Windows, a junction's too).
// Returns null if not a link.
// `@heap`: a fresh counted string the tracker frees.
// fs_is_symlink: does NOT follow; returns 1 only for the link itself.
// On Windows a junction counts: it redirects resolution
// exactly as a symlink does (any name-surrogate reparse
// point). Pure boolean query, no wrapper (matches
// file_exists).
// fs_unlink_raw: remove a file or symlink (NOT a directory).
extern fs_symlink_raw(target: string, link_path: string) -> int
// fs_hard_link_raw: a second name (`link_path`) for the file at `target`;
// same filesystem, files only. 1 on success.
extern fs_hard_link_raw(target: string, link_path: string) -> int
extern fs_readlink_raw(path: string) -> string @heap
// Both return a fresh counted path (or null). `@heap` so the heap-tracker
// frees it — without it the returned path leaks (caught by the
// macOS leaks gate).
extern fs_make_temp_dir_raw(dir: string, prefix: string) -> string @heap
extern fs_make_temp_file_raw(dir: string, prefix: string) -> string @heap
extern fs_is_symlink(path: string) -> int
// fs_is_socket: 1 if the path is a UNIX-domain socket (follows
// symlinks). POSIX only; returns 0 on Windows. Pure
// boolean query, no wrapper (matches fs_is_symlink). #1368
extern fs_is_socket(path: string) -> int
extern fs_unlink_raw(path: string) -> int
// Non-atomic binary write: fopen("wb") + fwrite(len bytes) + fclose.
// Binary-safe because length is explicit. Cheaper than fs_write_atomic_raw
// when a partial file on crash is acceptable — scratch writes, caches,
// and anywhere the destination isn't load-bearing for another process.
//
// These two and fs_pwrite_raw take `data: ptr`, not `string`, and are not
// exported (#2301): the wrappers pass a byte[] slice's raw data pointer.
// A `string` parameter routes through the AetherString unwrap, which would
// misread a payload beginning with the header's magic bytes as a header;
// and a heap string passed to a `ptr` parameter would write its header.
// Use write_binary / write_atomic / pwrite.
extern fs_write_binary_raw(path: string, data: ptr, length: int) -> int
// Durable write: write-to-tmp + fsync + rename over destination.
// Binary-safe — takes an explicit length so embedded NULs survive.
extern fs_write_atomic_raw(path: string, data: ptr, length: int) -> int
// POSIX rename(2). Callers pairing with write_atomic should keep
// `from` on the same filesystem as `to` for atomicity.
extern fs_rename_raw(from: string, to: string) -> int
// Split-accessor stat: call fs_try_stat first, then read the
// getters. kind encoding: see STAT_KIND_* below.
// Pair is thread-local so back-to-back calls on one thread are safe.
// #1378: the raw OS code behind the portable kind from the most recent fs
// call on this thread. 0 after a success. Branch on the KIND_* value; reach
// for this only when the exact number matters, such as telling EAGAIN from
// EWOULDBLOCK or putting the number in a log.
extern fs_last_os_error() -> int
extern fs_error_message(path: string, fallback: string) -> string
last_os_error() -> int {
return fs_last_os_error()
}
extern fs_try_stat(path: string) -> int
extern fs_get_stat_kind() -> int
// Values fs_get_stat_kind / dir_list_kind return. SOCKET/FIFO/DEVICE are
// POSIX-only (#1368); on Windows those nodes report OTHER. Additive — code
// that only tested FILE/DIR/SYMLINK/OTHER is unaffected.
const STAT_KIND_FILE = 1
const STAT_KIND_DIR = 2
const STAT_KIND_SYMLINK = 3
const STAT_KIND_OTHER = 4
const STAT_KIND_SOCKET = 5
const STAT_KIND_FIFO = 6
const STAT_KIND_DEVICE = 7
// fs.walk callback RETURN values — steer the traversal. Return one of these
// from the walk closure; they read at the call site so the prune/stop
// affordance is visible without hunting the doc comment (return 0 is the
// implicit "keep going" if you return nothing meaningful):
// WALK_CONTINUE (0) descend/visit normally
// WALK_SKIP_SUBTREE (1) on a directory, do NOT descend into it (prune) —
// the `find -prune` of `! -path '*/node_modules/*'`
// WALK_STOP (2) end the whole walk immediately
const WALK_CONTINUE = 0
const WALK_SKIP_SUBTREE = 1
const WALK_STOP = 2
// size/mtime are `long` (#1021): 64-bit sizes (no >= 2 GiB wrap) and
// Y2038-safe mtimes.
extern fs_get_stat_size() -> long
extern fs_get_stat_mtime() -> long
// Split-accessor statvfs (#1117): fs_try_statvfs first, then read the
// three byte-count getters. All `long` (exact bytes, 64-bit). Thread-local
// like the stat pair. fs_try_statvfs returns 0 on failure (incl. Windows).
extern fs_try_statvfs(path: string) -> int
extern fs_get_statvfs_total() -> long
extern fs_get_statvfs_free() -> long
extern fs_get_statvfs_avail() -> long
// Mount enumeration (#1118). fs_try_mounts loads a thread-local mount
// table and returns the entry count (-1 on failure); the per-entry
// getters return strings BORROWED from that table, valid until the
// next fs_try_mounts / fs_release_mounts on the same thread. Backends:
// Linux /proc/self/mountinfo (octal escapes decoded), macOS and the
// BSDs getmntinfo(3), Windows drive letters. Prefer the mounts()
// wrapper below.
extern fs_try_mounts() -> int
extern fs_get_mount_count() -> int
extern fs_get_mount_source(i: int) -> string
extern fs_get_mount_point(i: int) -> string
extern fs_get_mount_fstype(i: int) -> string
extern fs_get_mount_options(i: int) -> string
extern fs_release_mounts()
// Block-device info (#1118), Linux sysfs backend. Accepts "/dev/sda",
// "sda", or a partition ("sda1", "nvme0n1p2"; the removable flag
// resolves through the parent disk). Other platforms report
// unsupported through the block_info() wrapper's error slot, never a
// fabricated answer.
extern fs_try_block_info(dev: string) -> int
extern fs_get_block_size_bytes() -> long
extern fs_get_block_removable() -> int
extern fs_get_block_transport() -> string
// Split-accessor binary read: fs_try_read_binary reads the file into
// a TLS-owned buffer; fs_get_read_binary / fs_get_read_binary_length
// read that buffer borrowed. fs_release_read_binary frees early
// (otherwise it's released on the next fs_try_read_binary call).
// The buffer is bytes whose length C reports separately, not a C string,
// so the getter is a `ptr`: as a `string`, binding it to a local copied
// it up to the first NUL. Copy it with string_new_with_length(p, n), or
// call read_binary, which does.
extern fs_try_read_binary(path: string) -> int
extern fs_get_read_binary() -> ptr
extern fs_get_read_binary_length() -> int
extern fs_release_read_binary()
// Unified tuple-return shape (#271 + #273) — the canonical entry
// point that fs.read_binary wraps. Returns (bytes, length, err):
// (AetherString*, int, "") on success, (empty, 0, "<reason>") on
// failure.
//
// Position 0 (bytes) is `@heap`: the C side allocates a fresh
// AetherString via `string_new_with_length`. The destructured LHS
// owns the buffer; the heap-string-tracker frees it at function
// exit (or on reassignment) — same machinery `fs_realpath_raw`
// below relies on. Position 2 (err) stays default-borrow — the
// error message is a static C string literal.
//
// Earlier shape used `(ptr, int, string)` for position 0, which
// suppressed heap classification at every tuple-destructure site
// and silently leaked the bytes buffer at scope exit. Reported by
// the avn port (tuple-destructure-heap-classification.md) where it
// drove O(N²) RSS retention in avnserver.
extern fs_read_binary_tuple(path: string) -> (string @heap, int, string)
// Structured-error pilot (issue #392) — these externs return
// (value, kind, message) where kind is one of the KIND_* constants
// at the top of this module. fs_copy_raw zero-copies via the
// platform's best primitive (copy_file_range / sendfile / fcopyfile /
// CopyFileExW); falls back to an 8 MiB read/write loop on
// filesystems that reject the kernel primitives. See aether_fs.c for
// the full performance hierarchy.
extern fs_copy_raw(src: string, dst: string) -> (int, int, string)
// fs_move_raw — atomic rename(2) when same-fs, transparent
// copy + unlink fallback on EXDEV. Returns (1, KIND_OK, "") on
// success, (0, KIND_*, msg) on failure.
extern fs_move_raw(src: string, dst: string) -> (int, int, string)
// fs_realpath_raw — OS-canonicalise the path (deref every symlink,
// remove ./.. components). Returns (resolved_path, KIND_OK, "") on
// success, ("", KIND_*, msg) on failure.
//
// Position 0 (resolved_path) is `@heap`: a fresh counted string on
// every path, the empty one on failure (realpath(3) on POSIX, the
// GetFinalPathNameByHandleW result in UTF-8 on Windows). The
// destructured LHS owns it; the heap-string-tracker frees it at
// function exit (or on reassignment). Position 2 (msg) stays
// default-borrow — error message is a static string literal in
// the C source.
//
// Audited callers: only `fs.realpath` (the Aether wrapper below)
// passes the tuple through; no manual string.release on the
// resolved path anywhere in stdlib, tests/, examples/, tools/,
// or contrib/. See #420 follow-up.
extern fs_realpath_raw(path: string) -> (string @heap, int, string)
// fs_chmod_raw — POSIX chmod(2). On Windows only the user-write
// bit (0o200) is honoured (matches Python's os.chmod docs). Returns
// (1, KIND_OK, "") or (0, KIND_*, msg).
extern fs_chmod_raw(path: string, mode: int) -> (int, int, string)
extern dir_list_count(list: ptr) -> int
extern dir_list_get(list: ptr, index: int) -> string
// #966: file kind of entry `index`, straight from readdir's d_type — no
// stat(2) needed. Same encoding as file_stat's kind: 1 = regular file,
// 2 = directory, 3 = symlink (target not followed), 4 = other (fifo /
// socket / device). 0 = unknown: the filesystem didn't report a type
// (rare) — stat that entry to resolve it.
extern dir_list_kind(list: ptr, index: int) -> int
extern dir_list_free(list: @frees ptr)
// Path utilities - pure functions, never fail
extern path_join(path1: string, path2: string) -> string @heap
extern path_dirname(path: string) -> string @heap
extern path_basename(path: string) -> string @heap
extern path_extension(path: string) -> string @heap
extern path_is_absolute(path: string) -> int
// Lexical path ops (#632). Pure-string; never touch the filesystem.
extern path_clean(path: string) -> string @heap
extern path_is_within_base(base: string, target: string) -> int
extern path_rel(base: string, target: string) -> string @heap
// Platform path separator ("/" POSIX, "\\" Windows) — #1369.
extern path_separator() -> string
// Positional I/O (#640).
extern fs_pwrite_raw(file: ptr, data: ptr, length: int, offset: long) -> long
extern fs_pread_raw(file: ptr, length: int, offset: long) -> int
extern fs_pread_into_raw(file: ptr, buf: ptr, length: int, offset: long) -> int
extern fs_get_pread() -> ptr
extern fs_get_pread_length() -> int
extern fs_release_pread()
extern fs_ftruncate_raw(file: ptr, length: long) -> string
extern fs_fsync_raw(file: ptr) -> string
// Descriptor accessor (#1003). The OS-level fd inside an open handle,
// or -1 if the handle is closed/invalid.
extern file_fd_raw(file: ptr) -> int
// Glob: match files by pattern. Raw externs return ptr, NULL on failure.
extern fs_glob_raw(pattern: string) -> ptr
extern fs_glob_multi_raw(patterns: ptr) -> ptr
// #977: recursive walk + change notification. Raw externs; the Aether-native
// wrappers (walk / watch_open below) add the (value, err) surface. The walk
// callback is used only during the call (#2523): the caller keeps its
// environment and releases it once the walk returns.
extern fs_walk_raw(path: string, cb: @noescape ptr) -> int
extern fs_watch_open_raw(path: string) -> ptr
// Block up to timeout_ms (negative = forever): 1 = something changed,
// 0 = timeout, -1 = error / closed handle. Pending events are drained so
// one burst of changes reports once; changes between watch_open and
// watch_wait are queued, not lost.
extern fs_watch_wait(watch: ptr, timeout_ms: int) -> int
// Release the handle. Safe on null.
extern fs_watch_close(watch: ptr)
// string_concat used for duplicating borrowed strings. strlen-based —
// do NOT use for binary payloads (it truncates at the first embedded
// NUL). Length-aware reads use string_new_with_length.
extern string_concat(a: string, b: string) -> string @heap
extern string_length(str: string) -> int
extern string_char_at(str: string, index: int) -> int
extern string_substring(str: string, start: int, end: int) -> string @heap
// Length-preserving string constructor. Takes an explicit byte count
// so binary payloads with embedded NULs survive the copy. Returns a
// ref-counted AetherString with the exact byte content — consumers
// reading up to `length` see the full file.
extern string_new_with_length(data: ptr, length: size_t) -> string @heap
// ---- Go-style wrappers ----
// Open a file. Returns (handle, "") on success, (null, error) on failure.
// `mode` is fopen's ("r", "w", "a", "r+", ...); the handle carries bytes
// verbatim on every platform — on Windows it is opened binary whether or
// not the mode says 'b', like every other std.fs entry point, so a '\n'
// written through it is one byte on disk and pread/pwrite are byte-exact.
// A mode with an explicit 't' ("wt") asks for C's text mode and gets it.
open(path: string, mode: string) -> {
handle = file_open_raw(path, mode)
if handle == null {
return null, "cannot open file"
}
return handle, ""
}
// Close a handle `open` gave, and free it. Returns "" on success, or the
// reason: a write the close flushes can fail (a full disk, a lost network
// mount), and the data is then not on disk. `defer fs.close(h)` after a
// successful open is the usual shape (#3179).
close(handle: ptr) -> string {
if handle == null {
return "null handle"
}
if file_close_raw(handle) < 0 {
return "close failed: buffered data was not written"
}
return ""
}
// Read the whole of an open handle, from its start. Returns (text, "") on
// success, ("", error) on failure; the handle stays open (#3179).
read_all(handle: ptr) -> {
if handle == null {
return "", "null handle"
}
text = file_read_all_raw(handle)
if text == null {
return "", "read failed"
}
return text, ""
}
// Read the entire contents of a file at `path`. Opens, reads, closes.
// Returns (content, "") on success, ("", error) on failure.
//
// The error names the path and the cause — "<path>: No such file or
// directory", "<path>: Is a directory", "<path>: Permission denied" — rather
// than the single "cannot open file" this used to return for every cause.
//
// LIFETIME: the error string is BORROWED from thread-local storage and is only
// valid until this thread's next failed read. Print it, or copy it with
// `string.concat(err, "")`, before issuing another read — do NOT hold it across
// one. Do not free it. The text read is the caller's string, released like any
// other when its place lets it go (#3168).
read(path: string) -> {
// "rb", not "r": Windows text mode collapses "\r\n" back to "\n" and stops
// at the first Ctrl-Z (0x1A) byte, neither of which fs.read should do — it
// returns verbatim bytes on POSIX and must match. (read_binary already uses
// "rb".) The 'b' is a no-op on POSIX.
handle = file_open_raw(path, "rb")
if handle == 0 {
// Was the bare "cannot open file" — no path, no reason, so a missing
// file, a permission error and a sandbox denial were indistinguishable.
// fs_error_message reads errno while it is still this call's.
return "", fs_error_message(path, "cannot open file")
}
content = file_read_all_raw(handle)
if content == 0 {
file_close_raw(handle)
return "", fs_error_message(path, "cannot read file")
}
content_copy = string_concat(content, "")
file_close_raw(handle)
return content_copy, ""
}
// Write `content` to a file at `path`. Opens in write mode, writes, closes.
// Returns "" on success, error string on failure.
write(path: string, content: string) -> {
// "wb", not "w": on Windows text mode translates every '\n' into "\r\n",
// so fs.write would silently corrupt exact/binary content (e.g. writing
// "hello world\n" produced 13 bytes and a different sha256 than on POSIX).
// The 'b' is a no-op on POSIX, so this is verbatim-bytes on every platform.
handle = file_open_raw(path, "wb")
if handle == 0 {
return fs_error_message(path, "cannot open file for writing")
}
length = string_length(content)
ok = file_write_raw(handle, content, length)
if ok == 0 {
err = fs_error_message(path, "write failed")
file_close_raw(handle)
return err
}
closed = file_close_raw(handle)
if closed < 0 {
return fs_error_message(path, "close failed: buffered data was not written")
}
return ""
}
// Delete the file at `path`. Returns "" on success, error on failure.
delete(path: string) -> {
ok = file_delete_raw(path)
if ok == 0 {
return "cannot delete file"
}
return ""
}
// Return the size of the file at `path` in bytes, as `long` (#1021 —
// files >= 2 GiB used to wrap negative through the old int surface).
// Returns (size, "") on success, (0, error) on failure.
//
// The success arm returns FIRST: the first `return` statement pins the
// inferred tuple slot types, so the `long`-typed arm must come before
// the int-literal error arm or the size slot narrows back to int.
size(path: string) -> {
s = file_size_raw(path)
if s >= 0 {
return s, ""
}
return 0, "cannot stat file"
}
// Return the file's mtime as Unix epoch seconds.
// Returns (mtime, "") on success, (0, error) on failure. Distinguishes
// "stat failed" from "file's mtime is 0" (which the older `file_mtime`
// extern collapses into a single sentinel). Prefer this wrapper for
// new code; `file_mtime` stays for back-compat.
// Success arm first — same tuple-slot-inference constraint as `size`.
mtime(path: string) -> {
m = file_mtime_raw(path)
if m >= 0 {
return m, ""
}
return 0, "cannot stat file"
}
// Does anything exist at `path`? Returns 1 for any kind of
// filesystem entry (regular file, directory, symlink, fifo, ...),
// 0 if nothing is there or `path` is empty. Use this when you don't
// care whether the target is a file or a directory — for type-
// specific checks reach for `file.exists` (regular-file-only) or
// `dir.exists` (directory-only). Matches POSIX `test -e`.
exists(path: string) -> int {
return fs_path_exists(path)
}
// Create a directory. Returns "" on success, error on failure.
create_dir(path: string) -> {
ok = dir_create_raw(path)
if ok == 0 {
return "cannot create directory"
}
return ""
}
// Like `create_dir` but with an explicit POSIX-style mode (0777-masked).
// Use this when the directory needs to be private — e.g.
// `fs.create_dir_with_mode("/run/myapp/keys", 448)` for 0o700 — without
// the mkdir-then-chmod race the "always 0755 + shell out to chmod"
// workaround would open. Windows ignores the mode at the directory
// layer; the parameter is accepted for API portability.
create_dir_with_mode(path: string, mode: int) -> {
ok = dir_create_mode_raw(path, mode)
if ok == 0 {
return "cannot create directory"
}
return ""
}
// Delete a directory. Returns "" on success, error on failure.
delete_dir(path: string) -> {
ok = dir_delete_raw(path)
if ok == 0 {
return "cannot delete directory"
}
return ""
}
// `mkdir -p`: create `path` and any missing parent directories. Treats
// already-existing directories as success. Returns "" on success, error
// on failure.
mkdir_p(path: string) -> {
ok = fs_mkdir_p_raw(path)
if ok == 0 {
return "cannot mkdir -p"
}
return ""
}
// Create a symbolic link at `link_path` pointing to `target`. The target
// is recorded verbatim — relative targets stay relative. Returns "" on
// success, error on failure (e.g. `link_path` already exists). On Windows
// a relative target is resolved against the link's directory to decide
// whether the link is to a directory (Windows records that), the
// target's separators are stored as backslashes, and creating a link
// needs the privilege administrators hold and Developer Mode grants
// everyone; without it this fails.
symlink(target: string, link_path: string) -> {
ok = fs_symlink_raw(target, link_path)
if ok == 0 {
return "cannot create symlink"
}
return ""
}
// Hard link: `link_path` becomes another name for the file at `target`
// (same filesystem; not directories). Returns "" on success, error on
// failure (e.g. `link_path` already exists, or they are on different
// filesystems). Windows uses CreateHardLinkW (NTFS).
hard_link(target: string, link_path: string) -> {
ok = fs_hard_link_raw(target, link_path)
if ok == 0 {
return "cannot create hard link"
}
return ""
}
// Read a symbolic link. Returns (target, "") on success,
// ("", error) if `path` is not a symlink or can't be read.
readlink(path: string) -> {
target = fs_readlink_raw(path)
if target == null {
return "", "not a symlink"
}
// target is @heap-owned; hand it straight back (the copy this used to
// make left the C allocation to leak on every call).
return target, ""
}
// The documented defaults for make_temp_dir / make_temp_file. The C side only
// defaulted a NULL dir, so the empty string these document became the
// template "/<prefix>XXXXXX" at the filesystem root and failed.
extern os_temp_dir_raw() -> string @heap
fn temp_parent(dir: string) -> string {
if dir == "" {
return os_temp_dir_raw()
}
return dir
}
fn temp_prefix(prefix: string) -> string {
if prefix == "" {
return "ae"
}
return prefix
}
// make_temp_dir(dir, prefix) — atomically create and return a uniquely-named
// temp DIRECTORY under `dir`, name starting `prefix` (mkdtemp — no race). The
// caller owns it: clean up with remove_tree(). Returns (path, "") or ("", err).
// Empty `dir` → the OS temp dir (os.temp_dir); empty `prefix` → "ae".
make_temp_dir(dir: string, prefix: string) -> {
p = fs_make_temp_dir_raw(temp_parent(dir), temp_prefix(prefix))
if p == null { return "", "cannot create temp dir" }
return p, ""
}
// make_temp_file(dir, prefix) — atomically create and return a uniquely-named
// temp FILE under `dir` (mkstemp — created O_EXCL, no race). The caller owns
// it: delete() when done. Returns (path, "") or ("", err).
make_temp_file(dir: string, prefix: string) -> {
p = fs_make_temp_file_raw(temp_parent(dir), temp_prefix(prefix))
if p == null { return "", "cannot create temp file" }
// p is @heap-owned; hand it straight back (string_concat here would leak
// the original and double-allocate).
return p, ""
}
// Remove a file or symlink. Refuses to remove a directory — use
// `delete_dir` for that. Returns "" on success, error on failure.
unlink(path: string) -> {
ok = fs_unlink_raw(path)
if ok == 0 {
return "cannot unlink"
}
return ""
}
// List directory contents.
// Returns (DirList ptr, "") on success, (null, error) on failure.
// Caller must free the returned ptr with dir_list_free.
list_dir(path: string) -> {
list = dir_list_raw(path)
if list == null {
return null, "cannot list directory"
}
return list, ""
}
// Glob for files matching a pattern.
// Returns (DirList ptr, "") on success, (null, error) on failure.
glob(pattern: string) -> {
list = fs_glob_raw(pattern)
if list == null {
return null, "glob failed"
}
return list, ""
}
// Multi-pattern glob.
glob_multi(patterns: ptr) -> {
list = fs_glob_multi_raw(patterns)
if list == null {
return null, "glob failed"
}
return list, ""
}
// #977: recursive directory walk. Visits `path` itself first (depth 0), then
// every entry beneath it, calling `cb` per entry:
//
// n, err = fs.walk(root, |path: string, kind: int, depth: int| {
// // kind: 1 file / 2 dir / 3 symlink / 4 other (same as file_stat)
// return fs.WALK_CONTINUE // or WALK_SKIP_SUBTREE (prune this dir) /
// // WALK_STOP (end the walk). Raw: 0 / 1 / 2.
// })
//
// The callback's return PRUNES: WALK_SKIP_SUBTREE (1) on a directory means "do
// not descend into it" — the `find -prune` of `! -path '*/node_modules/*'`,
// without walking the excluded subtree first. WALK_STOP (2) ends the walk.
//
// One readdir sweep per directory — entry kinds come from d_type (#966), so
// nothing is stat'ed unless the filesystem doesn't report a type. Symlinks
// are reported but never followed (no cycles).
//
// `path` is BORROWED. It points into the one buffer the walk rewrites for the
// next entry, so it is only valid until the callback returns. Storing it
// directly keeps the pointer, not the bytes: `list.add(paths, path)` leaves a
// dangling pointer that reads as garbage long after the walk finished, and
// the corruption surfaces wherever the string is finally used rather than
// here. Copy at the boundary to keep a path:
//
// list.add(paths, string.copy(path))
//
// Traversal order within a directory is the platform's readdir order
// (unspecified).
// Returns (entries visited, "") or (0, error) when `path` can't be read.
walk(path: string, cb: fn) -> {
n = fs_walk_raw(path, cb)
if n < 0 {
return 0, "cannot walk path"
}
return n, ""
}
// #977: watch a directory (or file) for changes — create / delete / modify /
// rename inside it — over the platform primitive (kqueue on macOS/BSD,
// inotify on Linux, FindFirstChangeNotification on Windows). The event is a
// coarse "something changed here" ping: re-list the directory to see what.
// Non-recursive; one handle watches one path; a handle is single-threaded.
//
// w, err = fs.watch_open(dir)
// changed = fs.watch_wait(w, 1000) // 1 changed / 0 timeout / -1 error
// fs.watch_close(w)
//
// Changes that happen between watch_open and watch_wait are queued, not
// lost — so "open watch, do work, then wait" never misses an edit.
watch_open(path: string) -> {
w = fs_watch_open_raw(path)
if w == null {
return null, "cannot watch path"
}
return w, ""
}
// Block up to timeout_ms (negative = forever). 1 = changed, 0 = timeout,
// -1 = error / closed handle. Drains pending events so one burst of changes
// reports once.
watch_wait(watch: ptr, timeout_ms: int) -> int {
return fs_watch_wait(watch, timeout_ms)
}
// Release the watch handle. Safe on null.
watch_close(watch: ptr) {
fs_watch_close(watch)
}
// A slice with no bound (`p as byte[]`, `.len` -1) has no length to write.
fn unbounded_write(fname: string) {
panic("fs.${fname}: the slice has no bound (.len -1); give it one, as `(p as byte[])[0..n]`")
}
// Non-atomic binary write: open, write every byte of `data`, close.
// Binary-safe — the length travels with the slice (#2301), so embedded
// NULs survive. An empty slice writes an empty file.
//
// For a string, write its byte view: `fs.write_binary(path,
// string.bytes(s))`; for a `std.bytes` buffer, `bytes.view(buf)`; for a
// prefix, sub-slice it (`string.bytes(s)[0..n]`). Text that is never
// binary can use `fs.write` instead.
//
// When you want the write to be crash-safe, use `fs.write_atomic`
// instead (stage + fsync + rename). `write_binary` skips that
// machinery for cheaper writes to scratch paths, caches, or any
// destination where a partial file on crash is acceptable.
//
// Returns "" on success, error on failure (open / write / close).
// On failure, whatever bytes were written stay on disk — caller
// removes the partial file if needed.
write_binary(path: string, data: byte[]) -> string {
if data.len < 0 {
unbounded_write("write_binary")
}
ok = fs_write_binary_raw(path, data, data.len)
if ok == 0 {
return fs_error_message(path, "binary write failed")
}
return ""
}
// Durable write: stage `data` into a sibling tmp file, fsync, then
// rename(2) over `path`. On crash between write and rename, the
// destination is either the old contents or the new — never a
// partial write. Binary-safe: the length travels with the slice
// (#2301), so embedded NULs survive. For a string pass
// `string.bytes(s)`; for a `std.bytes` buffer, `bytes.view(buf)`.
//
// Returns "" on success, error on failure (tmp create, write, fsync,
// rename — the tmp is removed if any step fails so the filesystem
// isn't littered with aborted writes).
write_atomic(path: string, data: byte[]) -> {
if data.len < 0 {
unbounded_write("write_atomic")
}
ok = fs_write_atomic_raw(path, data, data.len)
if ok == 0 {
return fs_error_message(path, "atomic write failed")
}
return ""
}
// Rename `from` to `to` — thin POSIX rename(2) wrapper. Atomic when
// both sides are on the same filesystem. Returns "" on success,
// error on failure (e.g. cross-filesystem rename, destination dir
// not writable, source missing).
rename(from: string, to: string) -> {
ok = fs_rename_raw(from, to)
if ok == 0 {
// Both paths: the reason can be the destination's (a missing
// directory, no write permission there) as well as the source's.
return fs_error_message("${from} -> ${to}", "rename failed")
}
return ""
}
// Single-stat accessor. Returns (kind, size, mtime, "") on success,
// (0, 0, 0, error) on failure. `kind` is one of:
// 1 = file, 2 = directory, 3 = symlink, 4 = other (FIFO, socket,
// device, ...).
// `mtime` is a Unix timestamp, `size` is in bytes. Uses lstat(2) —
// symlinks report kind 3, the target is NOT followed.
//
// Cheaper than the existing file_exists + fs_is_symlink + size +
// file_mtime quartet when callers need more than one field.
// Two inference constraints keep size/mtime `long` here (#1021):
// the getters are bound to locals (a call expression directly inside
// a tuple return types as int; a variable carries the extern's
// declared long), and the success arm returns first (the first
// `return` pins the tuple slot types). The getters all return 0 after
// a failed fs_try_stat, so binding them before the ok-check is safe.
file_stat(path: string) -> {
ok = fs_try_stat(path)
kind = fs_get_stat_kind()
size = fs_get_stat_size()
mtime = fs_get_stat_mtime()
if ok != 0 {
return kind, size, mtime, ""
}
return 0, 0, 0, "cannot stat path"
}
// Exact filesystem byte counts for the filesystem containing `path` (#1117).
// Returns (total, free, avail, "") on success, (0, 0, 0, error) on failure.
// `avail` (POSIX f_bavail) is the space usable by an unprivileged process —
// the one you want for "how much can I actually write here" (e.g. auto-filling
// a write range: `end = avail / file_size`). POSIX statvfs(2); portable across
// Linux/macOS/BSD. Not available on Windows (returns the error branch there).
//
// Same `long`-inference discipline as file_stat (#1021): bind the getters to
// locals so they keep their `long` type, and return the success arm first so
// the first `return` pins the tuple slots to long. The getters all read 0
// after a failed fs_try_statvfs, so binding them before the ok-check is safe.
statvfs(path: string) -> {
ok = fs_try_statvfs(path)
total = fs_get_statvfs_total()
free = fs_get_statvfs_free()
avail = fs_get_statvfs_avail()
if ok != 0 {
return total, free, avail, ""
}
return 0, 0, 0, "cannot statvfs path"
}
// Load the mount table. Returns (count, "") on success or
// (0, "cannot enumerate mounts"). Read entries with mount_source /
// mount_point / mount_fstype / mount_options; free early with
// fs_release_mounts (otherwise the next mounts() call reuses the slot).
mounts() -> {
n = fs_try_mounts()
if n >= 0 {
return n, ""
}
return 0, "cannot enumerate mounts"
}
mount_source(i: int) -> string {
return fs_get_mount_source(i)
}
mount_point(i: int) -> string {
return fs_get_mount_point(i)
}
mount_fstype(i: int) -> string {
return fs_get_mount_fstype(i)
}
mount_options(i: int) -> string {
return fs_get_mount_options(i)
}
// Block-device facts. Returns (size_bytes, removable, transport, "")
// on success; removable is 1/0 or -1 when the kernel does not say.
// On platforms without a backend (everything but Linux today) returns
// (0, -1, "", "block info unavailable on this platform").
block_info(dev: string) -> {
ok = fs_try_block_info(dev)
size = fs_get_block_size_bytes()
removable = fs_get_block_removable()
transport = fs_get_block_transport()
if ok != 0 {
return size, removable, transport, ""
}
return 0, 0 - 1, "", "block info unavailable on this platform"
}
// Binary-safe file read. Preserves embedded NULs and reports the
// exact byte length. Returns (content, length, "") on success,
// ("", 0, error) on failure.
//
// The returned string is a length-aware copy: `string.length(content)`
// equals the returned `length` even when the payload contains NULs.
// Under the hood the copy goes through `string_new_with_length`
// rather than `string_concat`, which is strlen-based and would
// silently truncate at the first embedded NUL. The TLS buffer inside
// the runtime is released after the copy completes, so the caller
// doesn't have to manage lifetime.
//
// On failure the error names the path and the cause — "<path>: No such file
// or directory", "<path>: Permission denied", or, for a sandbox refusal,
// "<path>: blocked by sandbox policy (no fs_read grant for this path)". That
// last one is deliberately distinct: a policy refusal is not a filesystem
// failure, and reporting it as one sends people looking at the disk instead of
// at their grants.
//
// LIFETIME: the error string is BORROWED from thread-local storage, valid only
// until this thread's next failed read. Print it, or copy it with
// `string.concat(err, "")`, before issuing another read. Do not free it. The
// bytes are the caller's, released like any other string (#3168).
read_binary(path: string) -> {
// Single tuple-returning extern (#271 + #273). The four-extern
// split-accessor pattern (fs_try_read_binary + fs_get_read_binary
// + fs_get_read_binary_length + fs_release_read_binary) that this
// wrapper used to orchestrate is still in place for callers built
// directly against it; new bindings reach for the unified shape.
return fs_read_binary_tuple(path)
}
// Copy file contents from `src` to `dst`, preserving source mode bits
// (file owner is NOT changed). Returns (bytes_copied, kind, message):
// on success: (n, KIND_OK, "")
// on failure: (bytes_so_far, KIND_*, "<reason>")
//
// Symlinks in `src` are followed (matches POSIX `cp` without -P).
// `dst` is overwritten if it exists; if `dst` is an existing directory
// the call returns KIND_IS_DIR — we do not nest into it. `src` and
// `dst` must differ lexically; the call returns KIND_INVALID otherwise.
//