-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmodule.ae
More file actions
1021 lines (940 loc) · 42 KB
/
Copy pathmodule.ae
File metadata and controls
1021 lines (940 loc) · 42 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
//
// 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.
exports(
file_open_raw, file_close, file_read_all_raw, file_write_raw,
file_exists, fs_path_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_readlink_raw, fs_is_symlink, fs_is_socket, fs_unlink_raw,
STAT_KIND_FILE, STAT_KIND_DIR, STAT_KIND_SYMLINK, STAT_KIND_OTHER,
STAT_KIND_SOCKET, STAT_KIND_FIFO, STAT_KIND_DEVICE,
fs_write_binary_raw, fs_write_atomic_raw, 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_get_mount_source, fs_get_mount_point,
fs_get_mount_fstype, fs_get_mount_options, 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_clean, path_is_within_base, path_rel, path_separator,
clean, is_within_base, rel, join_clean, first_element,
fs_pwrite_raw, 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, read, write, delete, size, mtime, exists,
create_dir, create_dir_with_mode, delete_dir, mkdir_p,
symlink, 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,
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,
fs_last_os_error, last_os_error
)
// ---- 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(file: ptr) -> int
extern file_read_all_raw(file: ptr) -> string
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).
// fs_symlink_raw — create a symlink at `link_path` pointing to `target`.
// `target` is recorded verbatim (relative stays relative).
// fs_readlink_raw — read a symlink's target. Returns null if not a symlink.
// fs_is_symlink — does NOT follow; returns 1 only for the link itself.
// 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
extern fs_readlink_raw(path: string) -> string
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.
extern fs_write_binary_raw(path: string, data: string, 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: string, 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
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
// 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).
extern fs_try_read_binary(path: string) -> int
extern fs_get_read_binary() -> string
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`: realpath(3) on POSIX
// allocates a fresh buffer (POSIX.1-2008 extension); on Windows
// the GetFinalPathNameByHandleW result is converted to UTF-8 via
// a fresh malloc. The destructured LHS owns the buffer; 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: ptr)
// Path utilities - pure functions, never fail
extern path_join(path1: string, path2: string) -> string
extern path_dirname(path: string) -> string
extern path_basename(path: string) -> string
extern path_extension(path: string) -> string
extern path_is_absolute(path: string) -> int
// Lexical path ops (#632). Pure-string; never touch the filesystem.
extern path_clean(path: string) -> string
extern path_is_within_base(base: string, target: string) -> int
extern path_rel(base: string, target: string) -> string
// Platform path separator ("/" POSIX, "\\" Windows) — #1369.
extern path_separator() -> string
// Positional I/O (#640).
extern fs_pwrite_raw(file: ptr, data: string, 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() -> string
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.
extern fs_walk_raw(path: string, cb: 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
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
// 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: string, length: int) -> ptr
// ---- Go-style wrappers ----
// Open a file. Returns (handle, "") on success, (null, error) on failure.
open(path: string, mode: string) -> {
handle = file_open_raw(path, mode)
if handle == null {
return null, "cannot open file"
}
return handle, ""
}
// Read the entire contents of a file at `path`. Opens, reads, closes.
// Returns (content, "") on success, ("", error) on failure.
read(path: string) -> {
handle = file_open_raw(path, "r")
if handle == 0 {
return "", "cannot open file"
}
content = file_read_all_raw(handle)
if content == 0 {
file_close(handle)
return "", "cannot read file"
}
content_copy = string_concat(content, "")
file_close(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) -> {
handle = file_open_raw(path, "w")
if handle == 0 {
return "cannot open file for writing"
}
length = string_length(content)
ok = file_write_raw(handle, content, length)
file_close(handle)
if ok == 0 {
return "write failed"
}
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).
symlink(target: string, link_path: string) -> {
ok = fs_symlink_raw(target, link_path)
if ok == 0 {
return "cannot create symlink"
}
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_copy = string_concat(target, "")
return target_copy, ""
}
// 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 0 // 0 = continue, 1 = skip this dir's subtree, 2 = stop
// })
//
// 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 inside the
// callback — copy it (string.copy / list add) to keep it. 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: ptr) -> {
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)
}
// Non-atomic binary write: open, write exactly `length` bytes,
// close. Binary-safe — embedded NULs in `data` survive because
// the length is explicit (unlike `fs.write` which also works for
// AetherString inputs but trusts `string.length(content)` to
// report the right count).
//
// 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: string, length: int) -> string {
ok = fs_write_binary_raw(path, data, length)
if ok == 0 {
return "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: pass the explicit byte length so
// embedded NULs survive (the Aether string's own length is used at
// the call site, so callers normally just pass string.length(data)).
//
// 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: string, length: int) -> {
ok = fs_write_atomic_raw(path, data, length)
if ok == 0 {
return "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 {
return "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.
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.
//
// Performance: zero-copy primitives are tried in order
// (copy_file_range → sendfile on Linux; fcopyfile on macOS;
// CopyFileExW on Windows). An 8 MiB read/write loop is the portable
// fallback for filesystems that reject the kernel primitives. The
// reported byte count saturates at INT_MAX for files larger than
// 2^31 bytes — the data is still copied correctly; only the count is
// truncated.
copy(src: string, dst: string) -> {
return fs_copy_raw(src, dst)
}
// Move file from `src` to `dst`. Atomic on the same filesystem;
// transparently falls back to copy + unlink across filesystems
// (EXDEV). Returns (1, KIND_OK, "") on success, (0, KIND_*, msg) on
// failure. Cross-device directory moves surface as KIND_IS_DIR (the
// underlying copy refuses to recurse into directories — that needs
// a higher-level walker).
move(src: string, dst: string) -> {
return fs_move_raw(src, dst)
}
// OS-canonicalise the path: deref every symlink, fold . and ..
// components. Returns (resolved_path, KIND_OK, "") on success,
// ("", KIND_*, msg) on failure (KIND_NOT_FOUND if a component is
// missing, KIND_LOOP for symlink cycles, KIND_NAME_TOO_LONG if the
// resolved form exceeds the OS limit). The returned path is
// owned by the runtime; the caller does not need to free it.
realpath(path: string) -> {
return fs_realpath_raw(path)
}
// Change the permission bits at `path`. POSIX chmod(2) — follows
// symlinks. On Windows only the user-write bit (0o200) is honoured;
// every other bit is silently ignored (matches Python's os.chmod
// docs). `mode` is masked with 07777 internally. Returns
// (1, KIND_OK, "") or (0, KIND_*, msg).
chmod(path: string, mode: int) -> {
return fs_chmod_raw(path, mode)
}
// Lexically clean `path` per POSIX filepath.Clean semantics — collapse
// `//` and `./`, resolve `..` against a segment stack (drop the
// parent), preserve a leading `/`, preserve unresolved leading `..`
// on relative paths. Empty input → ".". Pure-string, no filesystem
// access.
//
// Examples:
// fs.clean("/a//b/./c/../d") → "/a/b/d"
// fs.clean("../../x") → "../../x" (relative, unresolved)
// fs.clean("/..") → "/" (rooted)
// fs.clean("") → "."
clean(path: string) -> string {
return path_clean(path)
}
// Lexically-cleaned join. `path_join(a, b)` followed by `clean` in one
// call — the path that actually hits the filesystem after a user-
// supplied segment is appended. Use this (not bare `path_join`) wherever
// `b` may contain `..` or `.` — object keys, archive entry names, any
// caller-controlled tail — so `join_clean("bucket", "a/../b")` collapses
// to "bucket/b" rather than leaving the traversal in place. Pair with
// `is_within_base` for the containment check.
//
// Empty-segment handling mirrors path_join's identity behaviour: an
// empty `a` or `b` cleans the other side alone (so the result is never
// a spurious "./x" or "x/.").
//
// Examples:
// fs.join_clean("bucket", "a/../b") → "bucket/b"
// fs.join_clean("/data", "x/./y") → "/data/x/y"
// fs.join_clean("", "a/../b") → "b"
// fs.join_clean("bucket", "") → "bucket"
join_clean(a: string, b: string) -> string {
if string_length(a) == 0 {
return path_clean(b)
}
if string_length(b) == 0 {
return path_clean(a)
}
return path_clean(path_join(a, b))
}
// First cleaned path segment. Cleans `path` then returns the leading
// component up to (but not including) the first "/". For a rooted path
// the leading "/" is dropped first, so `first_element("/a/b")` is "a".
// A path that cleans to "." or "/" yields "". Useful for splitting an
// object key into its top-level bucket/prefix after traversal has been
// neutralised.
//
// Examples:
// fs.first_element("a/b/c") → "a"
// fs.first_element("/a/b") → "a"
// fs.first_element("x/../y/z") → "y"
// fs.first_element("only") → "only"
// fs.first_element("/") → ""
first_element(path: string) -> string {
cleaned = path_clean(path)
start = 0
if string_length(cleaned) > 0 {
if string_char_at(cleaned, 0) == 47 { // leading '/'
start = 1
}
}
i = start
n = string_length(cleaned)
while i < n {
if string_char_at(cleaned, i) == 47 {
return string_substring(cleaned, start, i)
}
i = i + 1
}
return string_substring(cleaned, start, n)
}
// Lexical containment: does cleaned `target` lie under cleaned `base`?
// Returns 1 yes, 0 no. SECURITY-CRITICAL primitive for any code that
// resolves a user-supplied path against a data dir / static-asset
// root / archive extraction prefix — call this BEFORE open(2) to
// reject `../../etc/passwd` at the door.
//
// Pure-string: does NOT follow symlinks. A symlink under `base`
// pointing outside is an open-time concern this function does not
// address. For symlink-aware containment, use realpath on both sides
// first (one extra syscall per request) then call this.
//
// Examples:
// fs.is_within_base("/data", "/data/x/y") → 1
// fs.is_within_base("/data", "/data") → 1 (identical)
// fs.is_within_base("/data", "/data/../x") → 0 (cleans to /x)
// fs.is_within_base("/data", "/datax/y") → 0 (prefix but not subdir)
is_within_base(base: string, target: string) -> int {
return path_is_within_base(base, target)
}
// Relative path from cleaned `base` to cleaned `target` (Go
// filepath.Rel). Returns the relative path on success, "" when
// one is absolute and the other relative (no relative path exists).
// `base == target` returns ".".
//
// Useful for showing paths relative to a project root in logs / UI.
// Less security-critical than is_within_base — same lexical
// computation in a different shape.
rel(base: string, target: string) -> string {
return path_rel(base, target)
}
// Positional binary-safe write. Writes `length` bytes from `data` at
// `offset` bytes from the start of the file. Returns
// (written, "") on success, (-1, error) on failure. Loops on
// short writes (POSIX permits returning fewer bytes than asked).
// The file must be opened in a mode admitting writes — "r+", "w+",
// "w", "a+", "wb+", etc. — via `fs.open(path, mode)`.
//
// This is the "scatter-write" primitive — reconstructing a file from
// blocks fetched out of order (rsync, zsync, parallel downloads,
// sparse-file build). For sequential append, `fs.write` is simpler.
// Success arm first — same tuple-slot-inference constraint as `size`
// (the count slot is `long`).
pwrite(file: ptr, data: string, length: int, offset: long) -> {
n = fs_pwrite_raw(file, data, length, offset)
if n >= 0 {
return n, ""
}
return -1, "pwrite failed"
}
// Positional binary-safe read. Reads up to `length` bytes from
// `offset` into an owned AetherString. Returns (bytes, n, "") on
// success — `n` may be less than `length` if EOF was reached (short
// reads are NOT an error per the POSIX convention for sparse-file
// I/O). Returns ("", 0, error) on failure.
//
// Same tuple shape as fs.read_binary so destructuring stays
// consistent.
pread(file: ptr, length: int, offset: long) -> {
ok = fs_pread_raw(file, length, offset)
if ok == 0 {
return "", 0, "pread failed"
}
raw = fs_get_pread()
n = fs_get_pread_length()
owned = string_new_with_length(raw, n)
fs_release_pread()
return owned, n, ""
}
// Read up to `length` bytes at `offset` directly into the existing
// std.bytes buffer `buf` (a `bytes` handle), clamped to the buffer's
// capacity, with no per-call allocation or copy. After the call `buf`
// holds the bytes read and its length is the returned count, so
// bytes.get_le64 / a bytes.cursor can read them in place. This is the
// copy-free sibling of `pread` for a reused fixed-size block buffer
// (#1102): reuse one buffer across a loop instead of allocating a fresh
// string per block.
//
// Returns (n, err): `n` is the byte count (n == 0 = EOF, 0 < n < length =
// short read), `err` is "" on success or a message on I/O error. Same
// EOF / short-read / error distinction as `pread`.
pread_into(file: ptr, buf: ptr, length: int, offset: long) -> int! {
n = fs_pread_into_raw(file, buf, length, offset)
if n < 0 {
return 0, "pread_into failed"
}
return n, ""
}
// Set the file length to `length` bytes. Extends with zero bytes if
// the new length is greater than the current size. Returns "" on
// success, an error message on failure. Required at the end of an
// out-of-order reconstruction to clip trailing padding.
ftruncate(file: ptr, length: long) -> string {
return fs_ftruncate_raw(file, length)