-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathFile.zig
1788 lines (1582 loc) · 65.5 KB
/
File.zig
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
/// The OS-specific file descriptor or file handle.
handle: Handle,
pub const Handle = posix.fd_t;
pub const Mode = posix.mode_t;
pub const INode = posix.ino_t;
pub const Uid = posix.uid_t;
pub const Gid = posix.gid_t;
pub const Kind = enum {
block_device,
character_device,
directory,
named_pipe,
sym_link,
file,
unix_domain_socket,
whiteout,
door,
event_port,
unknown,
};
/// This is the default mode given to POSIX operating systems for creating
/// files. `0o666` is "-rw-rw-rw-" which is counter-intuitive at first,
/// since most people would expect "-rw-r--r--", for example, when using
/// the `touch` command, which would correspond to `0o644`. However, POSIX
/// libc implementations use `0o666` inside `fopen` and then rely on the
/// process-scoped "umask" setting to adjust this number for file creation.
pub const default_mode = switch (builtin.os.tag) {
.windows => 0,
.wasi => 0,
else => 0o666,
};
pub const OpenError = error{
SharingViolation,
PathAlreadyExists,
FileNotFound,
AccessDenied,
PipeBusy,
NoDevice,
NameTooLong,
/// WASI-only; file paths must be valid UTF-8.
InvalidUtf8,
/// Windows-only; file paths provided by the user must be valid WTF-8.
/// https://simonsapin.github.io/wtf-8/
InvalidWtf8,
/// On Windows, file paths cannot contain these characters:
/// '/', '*', '?', '"', '<', '>', '|'
BadPathName,
Unexpected,
/// On Windows, `\\server` or `\\server\share` was not found.
NetworkNotFound,
/// On Windows, antivirus software is enabled by default. It can be
/// disabled, but Windows Update sometimes ignores the user's preference
/// and re-enables it. When enabled, antivirus software on Windows
/// intercepts file system operations and makes them significantly slower
/// in addition to possibly failing with this error code.
AntivirusInterference,
} || posix.OpenError || posix.FlockError;
pub const OpenMode = enum {
read_only,
write_only,
read_write,
};
pub const Lock = enum {
none,
shared,
exclusive,
};
pub const OpenFlags = struct {
mode: OpenMode = .read_only,
/// Open the file with an advisory lock to coordinate with other processes
/// accessing it at the same time. An exclusive lock will prevent other
/// processes from acquiring a lock. A shared lock will prevent other
/// processes from acquiring a exclusive lock, but does not prevent
/// other process from getting their own shared locks.
///
/// The lock is advisory, except on Linux in very specific circumstances[1].
/// This means that a process that does not respect the locking API can still get access
/// to the file, despite the lock.
///
/// On these operating systems, the lock is acquired atomically with
/// opening the file:
/// * Darwin
/// * DragonFlyBSD
/// * FreeBSD
/// * Haiku
/// * NetBSD
/// * OpenBSD
/// On these operating systems, the lock is acquired via a separate syscall
/// after opening the file:
/// * Linux
/// * Windows
///
/// [1]: https://www.kernel.org/doc/Documentation/filesystems/mandatory-locking.txt
lock: Lock = .none,
/// Sets whether or not to wait until the file is locked to return. If set to true,
/// `error.WouldBlock` will be returned. Otherwise, the file will wait until the file
/// is available to proceed.
lock_nonblocking: bool = false,
/// Set this to allow the opened file to automatically become the
/// controlling TTY for the current process.
allow_ctty: bool = false,
pub fn isRead(self: OpenFlags) bool {
return self.mode != .write_only;
}
pub fn isWrite(self: OpenFlags) bool {
return self.mode != .read_only;
}
};
pub const CreateFlags = struct {
/// Whether the file will be created with read access.
read: bool = false,
/// If the file already exists, and is a regular file, and the access
/// mode allows writing, it will be truncated to length 0.
truncate: bool = true,
/// Ensures that this open call creates the file, otherwise causes
/// `error.PathAlreadyExists` to be returned.
exclusive: bool = false,
/// Open the file with an advisory lock to coordinate with other processes
/// accessing it at the same time. An exclusive lock will prevent other
/// processes from acquiring a lock. A shared lock will prevent other
/// processes from acquiring a exclusive lock, but does not prevent
/// other process from getting their own shared locks.
///
/// The lock is advisory, except on Linux in very specific circumstances[1].
/// This means that a process that does not respect the locking API can still get access
/// to the file, despite the lock.
///
/// On these operating systems, the lock is acquired atomically with
/// opening the file:
/// * Darwin
/// * DragonFlyBSD
/// * FreeBSD
/// * Haiku
/// * NetBSD
/// * OpenBSD
/// On these operating systems, the lock is acquired via a separate syscall
/// after opening the file:
/// * Linux
/// * Windows
///
/// [1]: https://www.kernel.org/doc/Documentation/filesystems/mandatory-locking.txt
lock: Lock = .none,
/// Sets whether or not to wait until the file is locked to return. If set to true,
/// `error.WouldBlock` will be returned. Otherwise, the file will wait until the file
/// is available to proceed.
lock_nonblocking: bool = false,
/// For POSIX systems this is the file system mode the file will
/// be created with. On other systems this is always 0.
mode: Mode = default_mode,
};
/// Upon success, the stream is in an uninitialized state. To continue using it,
/// you must use the open() function.
pub fn close(self: File) void {
if (is_windows) {
windows.CloseHandle(self.handle);
} else {
posix.close(self.handle);
}
}
pub const SyncError = posix.SyncError;
/// Blocks until all pending file contents and metadata modifications
/// for the file have been synchronized with the underlying filesystem.
///
/// Note that this does not ensure that metadata for the
/// directory containing the file has also reached disk.
pub fn sync(self: File) SyncError!void {
return posix.fsync(self.handle);
}
/// Test whether the file refers to a terminal.
/// See also `getOrEnableAnsiEscapeSupport` and `supportsAnsiEscapeCodes`.
pub fn isTty(self: File) bool {
return posix.isatty(self.handle);
}
pub fn isCygwinPty(file: File) bool {
if (builtin.os.tag != .windows) return false;
const handle = file.handle;
// If this is a MSYS2/cygwin pty, then it will be a named pipe with a name in one of these formats:
// msys-[...]-ptyN-[...]
// cygwin-[...]-ptyN-[...]
//
// Example: msys-1888ae32e00d56aa-pty0-to-master
// First, just check that the handle is a named pipe.
// This allows us to avoid the more costly NtQueryInformationFile call
// for handles that aren't named pipes.
{
var io_status: windows.IO_STATUS_BLOCK = undefined;
var device_info: windows.FILE_FS_DEVICE_INFORMATION = undefined;
const rc = windows.ntdll.NtQueryVolumeInformationFile(handle, &io_status, &device_info, @sizeOf(windows.FILE_FS_DEVICE_INFORMATION), .FileFsDeviceInformation);
switch (rc) {
.SUCCESS => {},
else => return false,
}
if (device_info.DeviceType != windows.FILE_DEVICE_NAMED_PIPE) return false;
}
const name_bytes_offset = @offsetOf(windows.FILE_NAME_INFO, "FileName");
// `NAME_MAX` UTF-16 code units (2 bytes each)
// This buffer may not be long enough to handle *all* possible paths
// (PATH_MAX_WIDE would be necessary for that), but because we only care
// about certain paths and we know they must be within a reasonable length,
// we can use this smaller buffer and just return false on any error from
// NtQueryInformationFile.
const num_name_bytes = windows.MAX_PATH * 2;
var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = [_]u8{0} ** (name_bytes_offset + num_name_bytes);
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const rc = windows.ntdll.NtQueryInformationFile(handle, &io_status_block, &name_info_bytes, @intCast(name_info_bytes.len), .FileNameInformation);
switch (rc) {
.SUCCESS => {},
.INVALID_PARAMETER => unreachable,
else => return false,
}
const name_info: *const windows.FILE_NAME_INFO = @ptrCast(&name_info_bytes);
const name_bytes = name_info_bytes[name_bytes_offset .. name_bytes_offset + name_info.FileNameLength];
const name_wide = std.mem.bytesAsSlice(u16, name_bytes);
// The name we get from NtQueryInformationFile will be prefixed with a '\', e.g. \msys-1888ae32e00d56aa-pty0-to-master
return (std.mem.startsWith(u16, name_wide, &[_]u16{ '\\', 'm', 's', 'y', 's', '-' }) or
std.mem.startsWith(u16, name_wide, &[_]u16{ '\\', 'c', 'y', 'g', 'w', 'i', 'n', '-' })) and
std.mem.indexOf(u16, name_wide, &[_]u16{ '-', 'p', 't', 'y' }) != null;
}
/// Returns whether or not ANSI escape codes will be treated as such,
/// and attempts to enable support for ANSI escape codes if necessary
/// (on Windows).
///
/// Returns `true` if ANSI escape codes are supported or support was
/// successfully enabled. Returns false if ANSI escape codes are not
/// supported or support was unable to be enabled.
///
/// See also `supportsAnsiEscapeCodes`.
pub fn getOrEnableAnsiEscapeSupport(self: File) bool {
if (builtin.os.tag == .windows) {
var original_console_mode: windows.DWORD = 0;
// For Windows Terminal, VT Sequences processing is enabled by default.
if (windows.kernel32.GetConsoleMode(self.handle, &original_console_mode) != 0) {
if (original_console_mode & windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0) return true;
// For Windows Console, VT Sequences processing support was added in Windows 10 build 14361, but disabled by default.
// https://devblogs.microsoft.com/commandline/tmux-support-arrives-for-bash-on-ubuntu-on-windows/
//
// Note: In Microsoft's example for enabling virtual terminal processing, it
// shows attempting to enable `DISABLE_NEWLINE_AUTO_RETURN` as well:
// https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#example-of-enabling-virtual-terminal-processing
// This is avoided because in the old Windows Console, that flag causes \n (as opposed to \r\n)
// to behave unexpectedly (the cursor moves down 1 row but remains on the same column).
// Additionally, the default console mode in Windows Terminal does not have
// `DISABLE_NEWLINE_AUTO_RETURN` set, so by only enabling `ENABLE_VIRTUAL_TERMINAL_PROCESSING`
// we end up matching the mode of Windows Terminal.
const requested_console_modes = windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING;
const console_mode = original_console_mode | requested_console_modes;
if (windows.kernel32.SetConsoleMode(self.handle, console_mode) != 0) return true;
}
return self.isCygwinPty();
}
return self.supportsAnsiEscapeCodes();
}
/// Test whether ANSI escape codes will be treated as such without
/// attempting to enable support for ANSI escape codes.
///
/// See also `getOrEnableAnsiEscapeSupport`.
pub fn supportsAnsiEscapeCodes(self: File) bool {
if (builtin.os.tag == .windows) {
var console_mode: windows.DWORD = 0;
if (windows.kernel32.GetConsoleMode(self.handle, &console_mode) != 0) {
if (console_mode & windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0) return true;
}
return self.isCygwinPty();
}
if (builtin.os.tag == .wasi) {
// WASI sanitizes stdout when fd is a tty so ANSI escape codes
// will not be interpreted as actual cursor commands, and
// stderr is always sanitized.
return false;
}
if (builtin.os.tag == .uefi) {
// UEFI has it's own way of terminal control without ANSI.
return false;
}
if (self.isTty()) {
if (self.handle == posix.STDOUT_FILENO or self.handle == posix.STDERR_FILENO) {
if (posix.getenvZ("TERM")) |term| {
if (std.mem.eql(u8, term, "dumb"))
return false;
}
}
return true;
}
return false;
}
pub const SetEndPosError = posix.TruncateError;
/// Shrinks or expands the file.
/// The file offset after this call is left unchanged.
pub fn setEndPos(self: File, length: u64) SetEndPosError!void {
try posix.ftruncate(self.handle, length);
}
pub const SeekError = posix.SeekError;
/// Repositions read/write file offset relative to the current offset.
/// TODO: integrate with async I/O
pub fn seekBy(self: File, offset: i64) SeekError!void {
return posix.lseek_CUR(self.handle, offset);
}
/// Repositions read/write file offset relative to the end.
/// TODO: integrate with async I/O
pub fn seekFromEnd(self: File, offset: i64) SeekError!void {
return posix.lseek_END(self.handle, offset);
}
/// Repositions read/write file offset relative to the beginning.
/// TODO: integrate with async I/O
pub fn seekTo(self: File, offset: u64) SeekError!void {
return posix.lseek_SET(self.handle, offset);
}
pub const GetSeekPosError = posix.SeekError || StatError;
/// TODO: integrate with async I/O
pub fn getPos(self: File) GetSeekPosError!u64 {
return posix.lseek_CUR_get(self.handle);
}
/// TODO: integrate with async I/O
pub fn getEndPos(self: File) GetSeekPosError!u64 {
if (builtin.os.tag == .windows) {
return windows.GetFileSizeEx(self.handle);
}
return (try self.stat()).size;
}
pub const ModeError = StatError;
/// TODO: integrate with async I/O
pub fn mode(self: File) ModeError!Mode {
if (builtin.os.tag == .windows) {
return 0;
}
return (try self.stat()).mode;
}
pub const Stat = struct {
/// A number that the system uses to point to the file metadata. This
/// number is not guaranteed to be unique across time, as some file
/// systems may reuse an inode after its file has been deleted. Some
/// systems may change the inode of a file over time.
///
/// On Linux, the inode is a structure that stores the metadata, and
/// the inode _number_ is what you see here: the index number of the
/// inode.
///
/// The FileIndex on Windows is similar. It is a number for a file that
/// is unique to each filesystem.
inode: INode,
size: u64,
/// This is available on POSIX systems and is always 0 otherwise.
mode: Mode,
kind: Kind,
/// Last access time in nanoseconds, relative to UTC 1970-01-01.
atime: i128,
/// Last modification time in nanoseconds, relative to UTC 1970-01-01.
mtime: i128,
/// Last status/metadata change time in nanoseconds, relative to UTC 1970-01-01.
ctime: i128,
pub fn fromPosix(st: posix.Stat) Stat {
const atime = st.atime();
const mtime = st.mtime();
const ctime = st.ctime();
return .{
.inode = st.ino,
.size = @bitCast(st.size),
.mode = st.mode,
.kind = k: {
const m = st.mode & posix.S.IFMT;
switch (m) {
posix.S.IFBLK => break :k .block_device,
posix.S.IFCHR => break :k .character_device,
posix.S.IFDIR => break :k .directory,
posix.S.IFIFO => break :k .named_pipe,
posix.S.IFLNK => break :k .sym_link,
posix.S.IFREG => break :k .file,
posix.S.IFSOCK => break :k .unix_domain_socket,
else => {},
}
if (builtin.os.tag.isSolarish()) switch (m) {
posix.S.IFDOOR => break :k .door,
posix.S.IFPORT => break :k .event_port,
else => {},
};
break :k .unknown;
},
.atime = @as(i128, atime.sec) * std.time.ns_per_s + atime.nsec,
.mtime = @as(i128, mtime.sec) * std.time.ns_per_s + mtime.nsec,
.ctime = @as(i128, ctime.sec) * std.time.ns_per_s + ctime.nsec,
};
}
pub fn fromLinux(stx: linux.Statx) Stat {
const atime = stx.atime;
const mtime = stx.mtime;
const ctime = stx.ctime;
return .{
.inode = stx.ino,
.size = stx.size,
.mode = stx.mode,
.kind = switch (stx.mode & linux.S.IFMT) {
linux.S.IFDIR => .directory,
linux.S.IFCHR => .character_device,
linux.S.IFBLK => .block_device,
linux.S.IFREG => .file,
linux.S.IFIFO => .named_pipe,
linux.S.IFLNK => .sym_link,
linux.S.IFSOCK => .unix_domain_socket,
else => .unknown,
},
.atime = @as(i128, atime.sec) * std.time.ns_per_s + atime.nsec,
.mtime = @as(i128, mtime.sec) * std.time.ns_per_s + mtime.nsec,
.ctime = @as(i128, ctime.sec) * std.time.ns_per_s + ctime.nsec,
};
}
pub fn fromWasi(st: std.os.wasi.filestat_t) Stat {
return .{
.inode = st.ino,
.size = @bitCast(st.size),
.mode = 0,
.kind = switch (st.filetype) {
.BLOCK_DEVICE => .block_device,
.CHARACTER_DEVICE => .character_device,
.DIRECTORY => .directory,
.SYMBOLIC_LINK => .sym_link,
.REGULAR_FILE => .file,
.SOCKET_STREAM, .SOCKET_DGRAM => .unix_domain_socket,
else => .unknown,
},
.atime = st.atim,
.mtime = st.mtim,
.ctime = st.ctim,
};
}
};
pub const StatError = posix.FStatError;
/// Returns `Stat` containing basic information about the `File`.
/// Use `metadata` to retrieve more detailed information (e.g. creation time, permissions).
/// TODO: integrate with async I/O
pub fn stat(self: File) StatError!Stat {
if (builtin.os.tag == .windows) {
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var info: windows.FILE_ALL_INFORMATION = undefined;
const rc = windows.ntdll.NtQueryInformationFile(self.handle, &io_status_block, &info, @sizeOf(windows.FILE_ALL_INFORMATION), .FileAllInformation);
switch (rc) {
.SUCCESS => {},
// Buffer overflow here indicates that there is more information available than was able to be stored in the buffer
// size provided. This is treated as success because the type of variable-length information that this would be relevant for
// (name, volume name, etc) we don't care about.
.BUFFER_OVERFLOW => {},
.INVALID_PARAMETER => unreachable,
.ACCESS_DENIED => return error.AccessDenied,
else => return windows.unexpectedStatus(rc),
}
return .{
.inode = info.InternalInformation.IndexNumber,
.size = @as(u64, @bitCast(info.StandardInformation.EndOfFile)),
.mode = 0,
.kind = if (info.BasicInformation.FileAttributes & windows.FILE_ATTRIBUTE_REPARSE_POINT != 0) reparse_point: {
var tag_info: windows.FILE_ATTRIBUTE_TAG_INFO = undefined;
const tag_rc = windows.ntdll.NtQueryInformationFile(self.handle, &io_status_block, &tag_info, @sizeOf(windows.FILE_ATTRIBUTE_TAG_INFO), .FileAttributeTagInformation);
switch (tag_rc) {
.SUCCESS => {},
// INFO_LENGTH_MISMATCH and ACCESS_DENIED are the only documented possible errors
// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/d295752f-ce89-4b98-8553-266d37c84f0e
.INFO_LENGTH_MISMATCH => unreachable,
.ACCESS_DENIED => return error.AccessDenied,
else => return windows.unexpectedStatus(rc),
}
if (tag_info.ReparseTag & windows.reparse_tag_name_surrogate_bit != 0) {
break :reparse_point .sym_link;
}
// Unknown reparse point
break :reparse_point .unknown;
} else if (info.BasicInformation.FileAttributes & windows.FILE_ATTRIBUTE_DIRECTORY != 0)
.directory
else
.file,
.atime = windows.fromSysTime(info.BasicInformation.LastAccessTime),
.mtime = windows.fromSysTime(info.BasicInformation.LastWriteTime),
.ctime = windows.fromSysTime(info.BasicInformation.ChangeTime),
};
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
const st = try std.os.fstat_wasi(self.handle);
return Stat.fromWasi(st);
}
if (builtin.os.tag == .linux) {
var stx = std.mem.zeroes(linux.Statx);
const rc = linux.statx(
self.handle,
"",
linux.AT.EMPTY_PATH,
linux.STATX_TYPE | linux.STATX_MODE | linux.STATX_ATIME | linux.STATX_MTIME | linux.STATX_CTIME,
&stx,
);
return switch (linux.E.init(rc)) {
.SUCCESS => Stat.fromLinux(stx),
.ACCES => unreachable,
.BADF => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.LOOP => unreachable,
.NAMETOOLONG => unreachable,
.NOENT => unreachable,
.NOMEM => error.SystemResources,
.NOTDIR => unreachable,
else => |err| posix.unexpectedErrno(err),
};
}
const st = try posix.fstat(self.handle);
return Stat.fromPosix(st);
}
pub const ChmodError = posix.FChmodError;
/// Changes the mode of the file.
/// The process must have the correct privileges in order to do this
/// successfully, or must have the effective user ID matching the owner
/// of the file.
pub fn chmod(self: File, new_mode: Mode) ChmodError!void {
try posix.fchmod(self.handle, new_mode);
}
pub const ChownError = posix.FChownError;
/// Changes the owner and group of the file.
/// The process must have the correct privileges in order to do this
/// successfully. The group may be changed by the owner of the file to
/// any group of which the owner is a member. If the owner or group is
/// specified as `null`, the ID is not changed.
pub fn chown(self: File, owner: ?Uid, group: ?Gid) ChownError!void {
try posix.fchown(self.handle, owner, group);
}
/// Cross-platform representation of permissions on a file.
/// The `readonly` and `setReadonly` are the only methods available across all platforms.
/// Platform-specific functionality is available through the `inner` field.
pub const Permissions = struct {
/// You may use the `inner` field to use platform-specific functionality
inner: switch (builtin.os.tag) {
.windows => PermissionsWindows,
else => PermissionsUnix,
},
const Self = @This();
/// Returns `true` if permissions represent an unwritable file.
/// On Unix, `true` is returned only if no class has write permissions.
pub fn readOnly(self: Self) bool {
return self.inner.readOnly();
}
/// Sets whether write permissions are provided.
/// On Unix, this affects *all* classes. If this is undesired, use `unixSet`.
/// This method *DOES NOT* set permissions on the filesystem: use `File.setPermissions(permissions)`
pub fn setReadOnly(self: *Self, read_only: bool) void {
self.inner.setReadOnly(read_only);
}
};
pub const PermissionsWindows = struct {
attributes: windows.DWORD,
const Self = @This();
/// Returns `true` if permissions represent an unwritable file.
pub fn readOnly(self: Self) bool {
return self.attributes & windows.FILE_ATTRIBUTE_READONLY != 0;
}
/// Sets whether write permissions are provided.
/// This method *DOES NOT* set permissions on the filesystem: use `File.setPermissions(permissions)`
pub fn setReadOnly(self: *Self, read_only: bool) void {
if (read_only) {
self.attributes |= windows.FILE_ATTRIBUTE_READONLY;
} else {
self.attributes &= ~@as(windows.DWORD, windows.FILE_ATTRIBUTE_READONLY);
}
}
};
pub const PermissionsUnix = struct {
mode: Mode,
const Self = @This();
/// Returns `true` if permissions represent an unwritable file.
/// `true` is returned only if no class has write permissions.
pub fn readOnly(self: Self) bool {
return self.mode & 0o222 == 0;
}
/// Sets whether write permissions are provided.
/// This affects *all* classes. If this is undesired, use `unixSet`.
/// This method *DOES NOT* set permissions on the filesystem: use `File.setPermissions(permissions)`
pub fn setReadOnly(self: *Self, read_only: bool) void {
if (read_only) {
self.mode &= ~@as(Mode, 0o222);
} else {
self.mode |= @as(Mode, 0o222);
}
}
pub const Class = enum(u2) {
user = 2,
group = 1,
other = 0,
};
pub const Permission = enum(u3) {
read = 0o4,
write = 0o2,
execute = 0o1,
};
/// Returns `true` if the chosen class has the selected permission.
/// This method is only available on Unix platforms.
pub fn unixHas(self: Self, class: Class, permission: Permission) bool {
const mask = @as(Mode, @intFromEnum(permission)) << @as(u3, @intFromEnum(class)) * 3;
return self.mode & mask != 0;
}
/// Sets the permissions for the chosen class. Any permissions set to `null` are left unchanged.
/// This method *DOES NOT* set permissions on the filesystem: use `File.setPermissions(permissions)`
pub fn unixSet(self: *Self, class: Class, permissions: struct {
read: ?bool = null,
write: ?bool = null,
execute: ?bool = null,
}) void {
const shift = @as(u3, @intFromEnum(class)) * 3;
if (permissions.read) |r| {
if (r) {
self.mode |= @as(Mode, 0o4) << shift;
} else {
self.mode &= ~(@as(Mode, 0o4) << shift);
}
}
if (permissions.write) |w| {
if (w) {
self.mode |= @as(Mode, 0o2) << shift;
} else {
self.mode &= ~(@as(Mode, 0o2) << shift);
}
}
if (permissions.execute) |x| {
if (x) {
self.mode |= @as(Mode, 0o1) << shift;
} else {
self.mode &= ~(@as(Mode, 0o1) << shift);
}
}
}
/// Returns a `Permissions` struct representing the permissions from the passed mode.
pub fn unixNew(new_mode: Mode) Self {
return Self{
.mode = new_mode,
};
}
};
pub const SetPermissionsError = ChmodError;
/// Sets permissions according to the provided `Permissions` struct.
/// This method is *NOT* available on WASI
pub fn setPermissions(self: File, permissions: Permissions) SetPermissionsError!void {
switch (builtin.os.tag) {
.windows => {
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var info = windows.FILE_BASIC_INFORMATION{
.CreationTime = 0,
.LastAccessTime = 0,
.LastWriteTime = 0,
.ChangeTime = 0,
.FileAttributes = permissions.inner.attributes,
};
const rc = windows.ntdll.NtSetInformationFile(
self.handle,
&io_status_block,
&info,
@sizeOf(windows.FILE_BASIC_INFORMATION),
.FileBasicInformation,
);
switch (rc) {
.SUCCESS => return,
.INVALID_HANDLE => unreachable,
.ACCESS_DENIED => return error.AccessDenied,
else => return windows.unexpectedStatus(rc),
}
},
.wasi => @compileError("Unsupported OS"), // Wasi filesystem does not *yet* support chmod
else => {
try self.chmod(permissions.inner.mode);
},
}
}
/// Cross-platform representation of file metadata.
/// Platform-specific functionality is available through the `inner` field.
pub const Metadata = struct {
/// Exposes platform-specific functionality.
inner: switch (builtin.os.tag) {
.windows => MetadataWindows,
.linux => MetadataLinux,
.wasi => MetadataWasi,
else => MetadataUnix,
},
const Self = @This();
/// Returns the size of the file
pub fn size(self: Self) u64 {
return self.inner.size();
}
/// Returns a `Permissions` struct, representing the permissions on the file
pub fn permissions(self: Self) Permissions {
return self.inner.permissions();
}
/// Returns the `Kind` of file.
/// On Windows, can only return: `.file`, `.directory`, `.sym_link` or `.unknown`
pub fn kind(self: Self) Kind {
return self.inner.kind();
}
/// Returns the last time the file was accessed in nanoseconds since UTC 1970-01-01
pub fn accessed(self: Self) i128 {
return self.inner.accessed();
}
/// Returns the time the file was modified in nanoseconds since UTC 1970-01-01
pub fn modified(self: Self) i128 {
return self.inner.modified();
}
/// Returns the time the file was created in nanoseconds since UTC 1970-01-01
/// On Windows, this cannot return null
/// On Linux, this returns null if the filesystem does not support creation times
/// On Unices, this returns null if the filesystem or OS does not support creation times
/// On MacOS, this returns the ctime if the filesystem does not support creation times; this is insanity, and yet another reason to hate on Apple
pub fn created(self: Self) ?i128 {
return self.inner.created();
}
};
pub const MetadataUnix = struct {
stat: posix.Stat,
const Self = @This();
/// Returns the size of the file
pub fn size(self: Self) u64 {
return @intCast(self.stat.size);
}
/// Returns a `Permissions` struct, representing the permissions on the file
pub fn permissions(self: Self) Permissions {
return .{ .inner = .{ .mode = self.stat.mode } };
}
/// Returns the `Kind` of the file
pub fn kind(self: Self) Kind {
if (builtin.os.tag == .wasi and !builtin.link_libc) return switch (self.stat.filetype) {
.BLOCK_DEVICE => .block_device,
.CHARACTER_DEVICE => .character_device,
.DIRECTORY => .directory,
.SYMBOLIC_LINK => .sym_link,
.REGULAR_FILE => .file,
.SOCKET_STREAM, .SOCKET_DGRAM => .unix_domain_socket,
else => .unknown,
};
const m = self.stat.mode & posix.S.IFMT;
switch (m) {
posix.S.IFBLK => return .block_device,
posix.S.IFCHR => return .character_device,
posix.S.IFDIR => return .directory,
posix.S.IFIFO => return .named_pipe,
posix.S.IFLNK => return .sym_link,
posix.S.IFREG => return .file,
posix.S.IFSOCK => return .unix_domain_socket,
else => {},
}
if (builtin.os.tag.isSolarish()) switch (m) {
posix.S.IFDOOR => return .door,
posix.S.IFPORT => return .event_port,
else => {},
};
return .unknown;
}
/// Returns the last time the file was accessed in nanoseconds since UTC 1970-01-01
pub fn accessed(self: Self) i128 {
const atime = self.stat.atime();
return @as(i128, atime.sec) * std.time.ns_per_s + atime.nsec;
}
/// Returns the last time the file was modified in nanoseconds since UTC 1970-01-01
pub fn modified(self: Self) i128 {
const mtime = self.stat.mtime();
return @as(i128, mtime.sec) * std.time.ns_per_s + mtime.nsec;
}
/// Returns the time the file was created in nanoseconds since UTC 1970-01-01.
/// Returns null if this is not supported by the OS or filesystem
pub fn created(self: Self) ?i128 {
if (!@hasDecl(@TypeOf(self.stat), "birthtime")) return null;
const birthtime = self.stat.birthtime();
// If the filesystem doesn't support this the value *should* be:
// On FreeBSD: nsec = 0, sec = -1
// On NetBSD and OpenBSD: nsec = 0, sec = 0
// On MacOS, it is set to ctime -- we cannot detect this!!
switch (builtin.os.tag) {
.freebsd => if (birthtime.sec == -1 and birthtime.nsec == 0) return null,
.netbsd, .openbsd => if (birthtime.sec == 0 and birthtime.nsec == 0) return null,
.macos => {},
else => @compileError("Creation time detection not implemented for OS"),
}
return @as(i128, birthtime.sec) * std.time.ns_per_s + birthtime.nsec;
}
};
/// `MetadataUnix`, but using Linux's `statx` syscall.
pub const MetadataLinux = struct {
statx: std.os.linux.Statx,
const Self = @This();
/// Returns the size of the file
pub fn size(self: Self) u64 {
return self.statx.size;
}
/// Returns a `Permissions` struct, representing the permissions on the file
pub fn permissions(self: Self) Permissions {
return Permissions{ .inner = PermissionsUnix{ .mode = self.statx.mode } };
}
/// Returns the `Kind` of the file
pub fn kind(self: Self) Kind {
const m = self.statx.mode & posix.S.IFMT;
switch (m) {
posix.S.IFBLK => return .block_device,
posix.S.IFCHR => return .character_device,
posix.S.IFDIR => return .directory,
posix.S.IFIFO => return .named_pipe,
posix.S.IFLNK => return .sym_link,
posix.S.IFREG => return .file,
posix.S.IFSOCK => return .unix_domain_socket,
else => {},
}
return .unknown;
}
/// Returns the last time the file was accessed in nanoseconds since UTC 1970-01-01
pub fn accessed(self: Self) i128 {
return @as(i128, self.statx.atime.sec) * std.time.ns_per_s + self.statx.atime.nsec;
}
/// Returns the last time the file was modified in nanoseconds since UTC 1970-01-01
pub fn modified(self: Self) i128 {
return @as(i128, self.statx.mtime.sec) * std.time.ns_per_s + self.statx.mtime.nsec;
}
/// Returns the time the file was created in nanoseconds since UTC 1970-01-01.
/// Returns null if this is not supported by the filesystem, or on kernels before than version 4.11
pub fn created(self: Self) ?i128 {
if (self.statx.mask & std.os.linux.STATX_BTIME == 0) return null;
return @as(i128, self.statx.btime.sec) * std.time.ns_per_s + self.statx.btime.nsec;
}
};
pub const MetadataWasi = struct {
stat: std.os.wasi.filestat_t,
pub fn size(self: @This()) u64 {
return self.stat.size;
}
pub fn permissions(self: @This()) Permissions {
return .{ .inner = .{ .mode = self.stat.mode } };
}
pub fn kind(self: @This()) Kind {
return switch (self.stat.filetype) {
.BLOCK_DEVICE => .block_device,
.CHARACTER_DEVICE => .character_device,
.DIRECTORY => .directory,
.SYMBOLIC_LINK => .sym_link,
.REGULAR_FILE => .file,
.SOCKET_STREAM, .SOCKET_DGRAM => .unix_domain_socket,
else => .unknown,
};
}
pub fn accessed(self: @This()) i128 {
return self.stat.atim;
}
pub fn modified(self: @This()) i128 {
return self.stat.mtim;
}
pub fn created(self: @This()) ?i128 {
return self.stat.ctim;
}
};
pub const MetadataWindows = struct {
attributes: windows.DWORD,
reparse_tag: windows.DWORD,
_size: u64,
access_time: i128,
modified_time: i128,
creation_time: i128,
const Self = @This();
/// Returns the size of the file
pub fn size(self: Self) u64 {
return self._size;
}
/// Returns a `Permissions` struct, representing the permissions on the file
pub fn permissions(self: Self) Permissions {
return .{ .inner = .{ .attributes = self.attributes } };
}
/// Returns the `Kind` of the file.
/// Can only return: `.file`, `.directory`, `.sym_link` or `.unknown`
pub fn kind(self: Self) Kind {
if (self.attributes & windows.FILE_ATTRIBUTE_REPARSE_POINT != 0) {
if (self.reparse_tag & windows.reparse_tag_name_surrogate_bit != 0) {
return .sym_link;
}
} else if (self.attributes & windows.FILE_ATTRIBUTE_DIRECTORY != 0) {
return .directory;
} else {
return .file;
}
return .unknown;