-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathtest.zig
2104 lines (1713 loc) · 80.2 KB
/
test.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
const std = @import("../std.zig");
const builtin = @import("builtin");
const testing = std.testing;
const fs = std.fs;
const mem = std.mem;
const wasi = std.os.wasi;
const native_os = builtin.os.tag;
const windows = std.os.windows;
const posix = std.posix;
const ArenaAllocator = std.heap.ArenaAllocator;
const Dir = std.fs.Dir;
const File = std.fs.File;
const tmpDir = testing.tmpDir;
const SymLinkFlags = std.fs.Dir.SymLinkFlags;
const PathType = enum {
relative,
absolute,
unc,
pub fn isSupported(self: PathType, target_os: std.Target.Os) bool {
return switch (self) {
.relative => true,
.absolute => std.os.isGetFdPathSupportedOnTarget(target_os),
.unc => target_os.tag == .windows,
};
}
pub const TransformError = posix.RealPathError || error{OutOfMemory};
pub const TransformFn = fn (allocator: mem.Allocator, dir: Dir, relative_path: [:0]const u8) TransformError![:0]const u8;
pub fn getTransformFn(comptime path_type: PathType) TransformFn {
switch (path_type) {
.relative => return struct {
fn transform(allocator: mem.Allocator, dir: Dir, relative_path: [:0]const u8) TransformError![:0]const u8 {
_ = allocator;
_ = dir;
return relative_path;
}
}.transform,
.absolute => return struct {
fn transform(allocator: mem.Allocator, dir: Dir, relative_path: [:0]const u8) TransformError![:0]const u8 {
// The final path may not actually exist which would cause realpath to fail.
// So instead, we get the path of the dir and join it with the relative path.
var fd_path_buf: [fs.max_path_bytes]u8 = undefined;
const dir_path = try std.os.getFdPath(dir.fd, &fd_path_buf);
return fs.path.joinZ(allocator, &.{ dir_path, relative_path });
}
}.transform,
.unc => return struct {
fn transform(allocator: mem.Allocator, dir: Dir, relative_path: [:0]const u8) TransformError![:0]const u8 {
// Any drive absolute path (C:\foo) can be converted into a UNC path by
// using '127.0.0.1' as the server name and '<drive letter>$' as the share name.
var fd_path_buf: [fs.max_path_bytes]u8 = undefined;
const dir_path = try std.os.getFdPath(dir.fd, &fd_path_buf);
const windows_path_type = windows.getUnprefixedPathType(u8, dir_path);
switch (windows_path_type) {
.unc_absolute => return fs.path.joinZ(allocator, &.{ dir_path, relative_path }),
.drive_absolute => {
// `C:\<...>` -> `\\127.0.0.1\C$\<...>`
const prepended = "\\\\127.0.0.1\\";
var path = try fs.path.joinZ(allocator, &.{ prepended, dir_path, relative_path });
path[prepended.len + 1] = '$';
return path;
},
else => unreachable,
}
}
}.transform,
}
}
};
const TestContext = struct {
path_type: PathType,
path_sep: u8,
arena: ArenaAllocator,
tmp: testing.TmpDir,
dir: std.fs.Dir,
transform_fn: *const PathType.TransformFn,
pub fn init(path_type: PathType, path_sep: u8, allocator: mem.Allocator, transform_fn: *const PathType.TransformFn) TestContext {
const tmp = tmpDir(.{ .iterate = true });
return .{
.path_type = path_type,
.path_sep = path_sep,
.arena = ArenaAllocator.init(allocator),
.tmp = tmp,
.dir = tmp.dir,
.transform_fn = transform_fn,
};
}
pub fn deinit(self: *TestContext) void {
self.arena.deinit();
self.tmp.cleanup();
}
/// Returns the `relative_path` transformed into the TestContext's `path_type`,
/// with any supported path separators replaced by `path_sep`.
/// The result is allocated by the TestContext's arena and will be free'd during
/// `TestContext.deinit`.
pub fn transformPath(self: *TestContext, relative_path: [:0]const u8) ![:0]const u8 {
const allocator = self.arena.allocator();
const transformed_path = try self.transform_fn(allocator, self.dir, relative_path);
if (native_os == .windows) {
const transformed_sep_path = try allocator.dupeZ(u8, transformed_path);
std.mem.replaceScalar(u8, transformed_sep_path, switch (self.path_sep) {
'/' => '\\',
'\\' => '/',
else => unreachable,
}, self.path_sep);
return transformed_sep_path;
}
return transformed_path;
}
/// Replaces any path separators with the canonical path separator for the platform
/// (e.g. all path separators are converted to `\` on Windows).
/// If path separators are replaced, then the result is allocated by the
/// TestContext's arena and will be free'd during `TestContext.deinit`.
pub fn toCanonicalPathSep(self: *TestContext, path: [:0]const u8) ![:0]const u8 {
if (native_os == .windows) {
const allocator = self.arena.allocator();
const transformed_sep_path = try allocator.dupeZ(u8, path);
std.mem.replaceScalar(u8, transformed_sep_path, '/', '\\');
return transformed_sep_path;
}
return path;
}
};
/// `test_func` must be a function that takes a `*TestContext` as a parameter and returns `!void`.
/// `test_func` will be called once for each PathType that the current target supports,
/// and will be passed a TestContext that can transform a relative path into the path type under test.
/// The TestContext will also create a tmp directory for you (and will clean it up for you too).
fn testWithAllSupportedPathTypes(test_func: anytype) !void {
try testWithPathTypeIfSupported(.relative, '/', test_func);
try testWithPathTypeIfSupported(.absolute, '/', test_func);
try testWithPathTypeIfSupported(.unc, '/', test_func);
try testWithPathTypeIfSupported(.relative, '\\', test_func);
try testWithPathTypeIfSupported(.absolute, '\\', test_func);
try testWithPathTypeIfSupported(.unc, '\\', test_func);
}
fn testWithPathTypeIfSupported(comptime path_type: PathType, comptime path_sep: u8, test_func: anytype) !void {
if (!(comptime path_type.isSupported(builtin.os))) return;
if (!(comptime fs.path.isSep(path_sep))) return;
var ctx = TestContext.init(path_type, path_sep, testing.allocator, path_type.getTransformFn());
defer ctx.deinit();
try test_func(&ctx);
}
// For use in test setup. If the symlink creation fails on Windows with
// AccessDenied, then make the test failure silent (it is not a Zig failure).
fn setupSymlink(dir: Dir, target: []const u8, link: []const u8, flags: SymLinkFlags) !void {
return dir.symLink(target, link, flags) catch |err| switch (err) {
// Symlink requires admin privileges on windows, so this test can legitimately fail.
error.AccessDenied => if (native_os == .windows) return error.SkipZigTest else return err,
else => return err,
};
}
// For use in test setup. If the symlink creation fails on Windows with
// AccessDenied, then make the test failure silent (it is not a Zig failure).
fn setupSymlinkAbsolute(target: []const u8, link: []const u8, flags: SymLinkFlags) !void {
return fs.symLinkAbsolute(target, link, flags) catch |err| switch (err) {
error.AccessDenied => if (native_os == .windows) return error.SkipZigTest else return err,
else => return err,
};
}
test "Dir.readLink" {
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
// Create some targets
const file_target_path = try ctx.transformPath("file.txt");
try ctx.dir.writeFile(.{ .sub_path = file_target_path, .data = "nonsense" });
const dir_target_path = try ctx.transformPath("subdir");
try ctx.dir.makeDir(dir_target_path);
// On Windows, symlink targets always use the canonical path separator
const canonical_file_target_path = try ctx.toCanonicalPathSep(file_target_path);
const canonical_dir_target_path = try ctx.toCanonicalPathSep(dir_target_path);
// test 1: symlink to a file
try setupSymlink(ctx.dir, file_target_path, "symlink1", .{});
try testReadLink(ctx.dir, canonical_file_target_path, "symlink1");
// test 2: symlink to a directory (can be different on Windows)
try setupSymlink(ctx.dir, dir_target_path, "symlink2", .{ .is_directory = true });
try testReadLink(ctx.dir, canonical_dir_target_path, "symlink2");
// test 3: relative path symlink
const parent_file = ".." ++ fs.path.sep_str ++ "target.txt";
const canonical_parent_file = try ctx.toCanonicalPathSep(parent_file);
var subdir = try ctx.dir.makeOpenPath("subdir", .{});
defer subdir.close();
try setupSymlink(subdir, canonical_parent_file, "relative-link.txt", .{});
try testReadLink(subdir, canonical_parent_file, "relative-link.txt");
}
}.impl);
}
fn testReadLink(dir: Dir, target_path: []const u8, symlink_path: []const u8) !void {
var buffer: [fs.max_path_bytes]u8 = undefined;
const actual = try dir.readLink(symlink_path, buffer[0..]);
try testing.expectEqualStrings(target_path, actual);
}
fn testReadLinkAbsolute(target_path: []const u8, symlink_path: []const u8) !void {
var buffer: [fs.max_path_bytes]u8 = undefined;
const given = try fs.readLinkAbsolute(symlink_path, buffer[0..]);
try testing.expectEqualStrings(target_path, given);
}
test "File.stat on a File that is a symlink returns Kind.sym_link" {
// This test requires getting a file descriptor of a symlink which
// is not possible on all targets
switch (builtin.target.os.tag) {
.windows, .linux => {},
else => return error.SkipZigTest,
}
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const dir_target_path = try ctx.transformPath("subdir");
try ctx.dir.makeDir(dir_target_path);
try setupSymlink(ctx.dir, dir_target_path, "symlink", .{ .is_directory = true });
var symlink = switch (builtin.target.os.tag) {
.windows => windows_symlink: {
const sub_path_w = try windows.cStrToPrefixedFileW(ctx.dir.fd, "symlink");
var result = Dir{
.fd = undefined,
};
const path_len_bytes = @as(u16, @intCast(sub_path_w.span().len * 2));
var nt_name = windows.UNICODE_STRING{
.Length = path_len_bytes,
.MaximumLength = path_len_bytes,
.Buffer = @constCast(&sub_path_w.data),
};
var attr = windows.OBJECT_ATTRIBUTES{
.Length = @sizeOf(windows.OBJECT_ATTRIBUTES),
.RootDirectory = if (fs.path.isAbsoluteWindowsW(sub_path_w.span())) null else ctx.dir.fd,
.Attributes = 0,
.ObjectName = &nt_name,
.SecurityDescriptor = null,
.SecurityQualityOfService = null,
};
var io: windows.IO_STATUS_BLOCK = undefined;
const rc = windows.ntdll.NtCreateFile(
&result.fd,
windows.STANDARD_RIGHTS_READ | windows.FILE_READ_ATTRIBUTES | windows.FILE_READ_EA | windows.SYNCHRONIZE | windows.FILE_TRAVERSE,
&attr,
&io,
null,
windows.FILE_ATTRIBUTE_NORMAL,
windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE | windows.FILE_SHARE_DELETE,
windows.FILE_OPEN,
// FILE_OPEN_REPARSE_POINT is the important thing here
windows.FILE_OPEN_REPARSE_POINT | windows.FILE_DIRECTORY_FILE | windows.FILE_SYNCHRONOUS_IO_NONALERT | windows.FILE_OPEN_FOR_BACKUP_INTENT,
null,
0,
);
switch (rc) {
.SUCCESS => break :windows_symlink result,
else => return windows.unexpectedStatus(rc),
}
},
.linux => linux_symlink: {
const sub_path_c = try posix.toPosixPath("symlink");
// the O_NOFOLLOW | O_PATH combination can obtain a fd to a symlink
// note that if O_DIRECTORY is set, then this will error with ENOTDIR
const flags: posix.O = .{
.NOFOLLOW = true,
.PATH = true,
.ACCMODE = .RDONLY,
.CLOEXEC = true,
};
const fd = try posix.openatZ(ctx.dir.fd, &sub_path_c, flags, 0);
break :linux_symlink Dir{ .fd = fd };
},
else => unreachable,
};
defer symlink.close();
const stat = try symlink.stat();
try testing.expectEqual(File.Kind.sym_link, stat.kind);
}
}.impl);
}
test "openDir" {
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const allocator = ctx.arena.allocator();
const subdir_path = try ctx.transformPath("subdir");
try ctx.dir.makeDir(subdir_path);
for ([_][]const u8{ "", ".", ".." }) |sub_path| {
const dir_path = try fs.path.join(allocator, &.{ subdir_path, sub_path });
var dir = try ctx.dir.openDir(dir_path, .{});
defer dir.close();
}
}
}.impl);
}
test "accessAbsolute" {
if (native_os == .wasi) return error.SkipZigTest;
var tmp = tmpDir(.{});
defer tmp.cleanup();
var arena = ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
const base_path = blk: {
const relative_path = try fs.path.join(allocator, &.{ ".zig-cache", "tmp", tmp.sub_path[0..] });
break :blk try fs.realpathAlloc(allocator, relative_path);
};
try fs.accessAbsolute(base_path, .{});
}
test "openDirAbsolute" {
if (native_os == .wasi) return error.SkipZigTest;
var tmp = tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.makeDir("subdir");
var arena = ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
const base_path = blk: {
const relative_path = try fs.path.join(allocator, &.{ ".zig-cache", "tmp", tmp.sub_path[0..], "subdir" });
break :blk try fs.realpathAlloc(allocator, relative_path);
};
{
var dir = try fs.openDirAbsolute(base_path, .{});
defer dir.close();
}
for ([_][]const u8{ ".", ".." }) |sub_path| {
const dir_path = try fs.path.join(allocator, &.{ base_path, sub_path });
var dir = try fs.openDirAbsolute(dir_path, .{});
defer dir.close();
}
}
test "openDir cwd parent '..'" {
if (native_os == .wasi) return error.SkipZigTest;
var dir = try fs.cwd().openDir("..", .{});
defer dir.close();
}
test "openDir non-cwd parent '..'" {
switch (native_os) {
.wasi, .netbsd, .openbsd => return error.SkipZigTest,
else => {},
}
var tmp = tmpDir(.{});
defer tmp.cleanup();
var subdir = try tmp.dir.makeOpenPath("subdir", .{});
defer subdir.close();
var dir = try subdir.openDir("..", .{});
defer dir.close();
const expected_path = try tmp.dir.realpathAlloc(testing.allocator, ".");
defer testing.allocator.free(expected_path);
const actual_path = try dir.realpathAlloc(testing.allocator, ".");
defer testing.allocator.free(actual_path);
try testing.expectEqualStrings(expected_path, actual_path);
}
test "readLinkAbsolute" {
if (native_os == .wasi) return error.SkipZigTest;
var tmp = tmpDir(.{});
defer tmp.cleanup();
// Create some targets
try tmp.dir.writeFile(.{ .sub_path = "file.txt", .data = "nonsense" });
try tmp.dir.makeDir("subdir");
// Get base abs path
var arena = ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
const base_path = blk: {
const relative_path = try fs.path.join(allocator, &.{ ".zig-cache", "tmp", tmp.sub_path[0..] });
break :blk try fs.realpathAlloc(allocator, relative_path);
};
{
const target_path = try fs.path.join(allocator, &.{ base_path, "file.txt" });
const symlink_path = try fs.path.join(allocator, &.{ base_path, "symlink1" });
// Create symbolic link by path
try setupSymlinkAbsolute(target_path, symlink_path, .{});
try testReadLinkAbsolute(target_path, symlink_path);
}
{
const target_path = try fs.path.join(allocator, &.{ base_path, "subdir" });
const symlink_path = try fs.path.join(allocator, &.{ base_path, "symlink2" });
// Create symbolic link to a directory by path
try setupSymlinkAbsolute(target_path, symlink_path, .{ .is_directory = true });
try testReadLinkAbsolute(target_path, symlink_path);
}
}
test "Dir.Iterator" {
var tmp_dir = tmpDir(.{ .iterate = true });
defer tmp_dir.cleanup();
// First, create a couple of entries to iterate over.
const file = try tmp_dir.dir.createFile("some_file", .{});
file.close();
try tmp_dir.dir.makeDir("some_dir");
var arena = ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var entries = std.ArrayList(Dir.Entry).init(allocator);
// Create iterator.
var iter = tmp_dir.dir.iterate();
while (try iter.next()) |entry| {
// We cannot just store `entry` as on Windows, we're re-using the name buffer
// which means we'll actually share the `name` pointer between entries!
const name = try allocator.dupe(u8, entry.name);
try entries.append(Dir.Entry{ .name = name, .kind = entry.kind });
}
try testing.expectEqual(@as(usize, 2), entries.items.len); // note that the Iterator skips '.' and '..'
try testing.expect(contains(&entries, .{ .name = "some_file", .kind = .file }));
try testing.expect(contains(&entries, .{ .name = "some_dir", .kind = .directory }));
}
test "Dir.Iterator many entries" {
var tmp_dir = tmpDir(.{ .iterate = true });
defer tmp_dir.cleanup();
const num = 1024;
var i: usize = 0;
var buf: [4]u8 = undefined; // Enough to store "1024".
while (i < num) : (i += 1) {
const name = try std.fmt.bufPrint(&buf, "{}", .{i});
const file = try tmp_dir.dir.createFile(name, .{});
file.close();
}
var arena = ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var entries = std.ArrayList(Dir.Entry).init(allocator);
// Create iterator.
var iter = tmp_dir.dir.iterate();
while (try iter.next()) |entry| {
// We cannot just store `entry` as on Windows, we're re-using the name buffer
// which means we'll actually share the `name` pointer between entries!
const name = try allocator.dupe(u8, entry.name);
try entries.append(.{ .name = name, .kind = entry.kind });
}
i = 0;
while (i < num) : (i += 1) {
const name = try std.fmt.bufPrint(&buf, "{}", .{i});
try testing.expect(contains(&entries, .{ .name = name, .kind = .file }));
}
}
test "Dir.Iterator twice" {
var tmp_dir = tmpDir(.{ .iterate = true });
defer tmp_dir.cleanup();
// First, create a couple of entries to iterate over.
const file = try tmp_dir.dir.createFile("some_file", .{});
file.close();
try tmp_dir.dir.makeDir("some_dir");
var arena = ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
var i: u8 = 0;
while (i < 2) : (i += 1) {
var entries = std.ArrayList(Dir.Entry).init(allocator);
// Create iterator.
var iter = tmp_dir.dir.iterate();
while (try iter.next()) |entry| {
// We cannot just store `entry` as on Windows, we're re-using the name buffer
// which means we'll actually share the `name` pointer between entries!
const name = try allocator.dupe(u8, entry.name);
try entries.append(Dir.Entry{ .name = name, .kind = entry.kind });
}
try testing.expectEqual(@as(usize, 2), entries.items.len); // note that the Iterator skips '.' and '..'
try testing.expect(contains(&entries, .{ .name = "some_file", .kind = .file }));
try testing.expect(contains(&entries, .{ .name = "some_dir", .kind = .directory }));
}
}
test "Dir.Iterator reset" {
var tmp_dir = tmpDir(.{ .iterate = true });
defer tmp_dir.cleanup();
// First, create a couple of entries to iterate over.
const file = try tmp_dir.dir.createFile("some_file", .{});
file.close();
try tmp_dir.dir.makeDir("some_dir");
var arena = ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
// Create iterator.
var iter = tmp_dir.dir.iterate();
var i: u8 = 0;
while (i < 2) : (i += 1) {
var entries = std.ArrayList(Dir.Entry).init(allocator);
while (try iter.next()) |entry| {
// We cannot just store `entry` as on Windows, we're re-using the name buffer
// which means we'll actually share the `name` pointer between entries!
const name = try allocator.dupe(u8, entry.name);
try entries.append(.{ .name = name, .kind = entry.kind });
}
try testing.expectEqual(@as(usize, 2), entries.items.len); // note that the Iterator skips '.' and '..'
try testing.expect(contains(&entries, .{ .name = "some_file", .kind = .file }));
try testing.expect(contains(&entries, .{ .name = "some_dir", .kind = .directory }));
iter.reset();
}
}
test "Dir.Iterator but dir is deleted during iteration" {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
// Create directory and setup an iterator for it
var subdir = try tmp.dir.makeOpenPath("subdir", .{ .iterate = true });
defer subdir.close();
var iterator = subdir.iterate();
// Create something to iterate over within the subdir
try tmp.dir.makePath("subdir" ++ fs.path.sep_str ++ "b");
// Then, before iterating, delete the directory that we're iterating.
// This is a contrived reproduction, but this could happen outside of the program, in another thread, etc.
// If we get an error while trying to delete, we can skip this test (this will happen on platforms
// like Windows which will give FileBusy if the directory is currently open for iteration).
tmp.dir.deleteTree("subdir") catch return error.SkipZigTest;
// Now, when we try to iterate, the next call should return null immediately.
const entry = try iterator.next();
try std.testing.expect(entry == null);
// On Linux, we can opt-in to receiving a more specific error by calling `nextLinux`
if (native_os == .linux) {
try std.testing.expectError(error.DirNotFound, iterator.nextLinux());
}
}
fn entryEql(lhs: Dir.Entry, rhs: Dir.Entry) bool {
return mem.eql(u8, lhs.name, rhs.name) and lhs.kind == rhs.kind;
}
fn contains(entries: *const std.ArrayList(Dir.Entry), el: Dir.Entry) bool {
for (entries.items) |entry| {
if (entryEql(entry, el)) return true;
}
return false;
}
test "Dir.realpath smoke test" {
if (!comptime std.os.isGetFdPathSupportedOnTarget(builtin.os)) return error.SkipZigTest;
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const allocator = ctx.arena.allocator();
const test_file_path = try ctx.transformPath("test_file");
const test_dir_path = try ctx.transformPath("test_dir");
var buf: [fs.max_path_bytes]u8 = undefined;
// FileNotFound if the path doesn't exist
try testing.expectError(error.FileNotFound, ctx.dir.realpathAlloc(allocator, test_file_path));
try testing.expectError(error.FileNotFound, ctx.dir.realpath(test_file_path, &buf));
try testing.expectError(error.FileNotFound, ctx.dir.realpathAlloc(allocator, test_dir_path));
try testing.expectError(error.FileNotFound, ctx.dir.realpath(test_dir_path, &buf));
// Now create the file and dir
try ctx.dir.writeFile(.{ .sub_path = test_file_path, .data = "" });
try ctx.dir.makeDir(test_dir_path);
const base_path = try ctx.transformPath(".");
const base_realpath = try ctx.dir.realpathAlloc(allocator, base_path);
const expected_file_path = try fs.path.join(
allocator,
&.{ base_realpath, "test_file" },
);
const expected_dir_path = try fs.path.join(
allocator,
&.{ base_realpath, "test_dir" },
);
// First, test non-alloc version
{
const file_path = try ctx.dir.realpath(test_file_path, &buf);
try testing.expectEqualStrings(expected_file_path, file_path);
const dir_path = try ctx.dir.realpath(test_dir_path, &buf);
try testing.expectEqualStrings(expected_dir_path, dir_path);
}
// Next, test alloc version
{
const file_path = try ctx.dir.realpathAlloc(allocator, test_file_path);
try testing.expectEqualStrings(expected_file_path, file_path);
const dir_path = try ctx.dir.realpathAlloc(allocator, test_dir_path);
try testing.expectEqualStrings(expected_dir_path, dir_path);
}
}
}.impl);
}
test "readAllAlloc" {
var tmp_dir = tmpDir(.{});
defer tmp_dir.cleanup();
var file = try tmp_dir.dir.createFile("test_file", .{ .read = true });
defer file.close();
const buf1 = try file.readToEndAlloc(testing.allocator, 1024);
defer testing.allocator.free(buf1);
try testing.expectEqual(@as(usize, 0), buf1.len);
const write_buf: []const u8 = "this is a test.\nthis is a test.\nthis is a test.\nthis is a test.\n";
try file.writeAll(write_buf);
try file.seekTo(0);
// max_bytes > file_size
const buf2 = try file.readToEndAlloc(testing.allocator, 1024);
defer testing.allocator.free(buf2);
try testing.expectEqual(write_buf.len, buf2.len);
try testing.expectEqualStrings(write_buf, buf2);
try file.seekTo(0);
// max_bytes == file_size
const buf3 = try file.readToEndAlloc(testing.allocator, write_buf.len);
defer testing.allocator.free(buf3);
try testing.expectEqual(write_buf.len, buf3.len);
try testing.expectEqualStrings(write_buf, buf3);
try file.seekTo(0);
// max_bytes < file_size
try testing.expectError(error.FileTooBig, file.readToEndAlloc(testing.allocator, write_buf.len - 1));
}
test "Dir.statFile" {
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const test_file_name = try ctx.transformPath("test_file");
try testing.expectError(error.FileNotFound, ctx.dir.statFile(test_file_name));
try ctx.dir.writeFile(.{ .sub_path = test_file_name, .data = "" });
const stat = try ctx.dir.statFile(test_file_name);
try testing.expectEqual(File.Kind.file, stat.kind);
}
}.impl);
}
test "statFile on dangling symlink" {
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const symlink_name = try ctx.transformPath("dangling-symlink");
const symlink_target = "." ++ fs.path.sep_str ++ "doesnotexist";
try setupSymlink(ctx.dir, symlink_target, symlink_name, .{});
try std.testing.expectError(error.FileNotFound, ctx.dir.statFile(symlink_name));
}
}.impl);
}
test "directory operations on files" {
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const test_file_name = try ctx.transformPath("test_file");
var file = try ctx.dir.createFile(test_file_name, .{ .read = true });
file.close();
try testing.expectError(error.PathAlreadyExists, ctx.dir.makeDir(test_file_name));
try testing.expectError(error.NotDir, ctx.dir.openDir(test_file_name, .{}));
try testing.expectError(error.NotDir, ctx.dir.deleteDir(test_file_name));
if (ctx.path_type == .absolute and comptime PathType.absolute.isSupported(builtin.os)) {
try testing.expectError(error.PathAlreadyExists, fs.makeDirAbsolute(test_file_name));
try testing.expectError(error.NotDir, fs.deleteDirAbsolute(test_file_name));
}
// ensure the file still exists and is a file as a sanity check
file = try ctx.dir.openFile(test_file_name, .{});
const stat = try file.stat();
try testing.expectEqual(File.Kind.file, stat.kind);
file.close();
}
}.impl);
}
test "file operations on directories" {
// TODO: fix this test on FreeBSD. https://github.com/ziglang/zig/issues/1759
if (native_os == .freebsd) return error.SkipZigTest;
if (native_os == .wasi and builtin.link_libc) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/20747
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const test_dir_name = try ctx.transformPath("test_dir");
try ctx.dir.makeDir(test_dir_name);
try testing.expectError(error.IsDir, ctx.dir.createFile(test_dir_name, .{}));
try testing.expectError(error.IsDir, ctx.dir.deleteFile(test_dir_name));
switch (native_os) {
// no error when reading a directory.
.dragonfly, .netbsd => {},
// Currently, WASI will return error.Unexpected (via ENOTCAPABLE) when attempting fd_read on a directory handle.
// TODO: Re-enable on WASI once https://github.com/bytecodealliance/wasmtime/issues/1935 is resolved.
.wasi => {},
else => {
try testing.expectError(error.IsDir, ctx.dir.readFileAlloc(testing.allocator, test_dir_name, std.math.maxInt(usize)));
},
}
// Note: The `.mode = .read_write` is necessary to ensure the error occurs on all platforms.
// TODO: Add a read-only test as well, see https://github.com/ziglang/zig/issues/5732
try testing.expectError(error.IsDir, ctx.dir.openFile(test_dir_name, .{ .mode = .read_write }));
if (ctx.path_type == .absolute and comptime PathType.absolute.isSupported(builtin.os)) {
try testing.expectError(error.IsDir, fs.createFileAbsolute(test_dir_name, .{}));
try testing.expectError(error.IsDir, fs.deleteFileAbsolute(test_dir_name));
}
// ensure the directory still exists as a sanity check
var dir = try ctx.dir.openDir(test_dir_name, .{});
dir.close();
}
}.impl);
}
test "makeOpenPath parent dirs do not exist" {
var tmp_dir = tmpDir(.{});
defer tmp_dir.cleanup();
var dir = try tmp_dir.dir.makeOpenPath("root_dir/parent_dir/some_dir", .{});
dir.close();
// double check that the full directory structure was created
var dir_verification = try tmp_dir.dir.openDir("root_dir/parent_dir/some_dir", .{});
dir_verification.close();
}
test "deleteDir" {
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const test_dir_path = try ctx.transformPath("test_dir");
const test_file_path = try ctx.transformPath("test_dir" ++ fs.path.sep_str ++ "test_file");
// deleting a non-existent directory
try testing.expectError(error.FileNotFound, ctx.dir.deleteDir(test_dir_path));
// deleting a non-empty directory
try ctx.dir.makeDir(test_dir_path);
try ctx.dir.writeFile(.{ .sub_path = test_file_path, .data = "" });
try testing.expectError(error.DirNotEmpty, ctx.dir.deleteDir(test_dir_path));
// deleting an empty directory
try ctx.dir.deleteFile(test_file_path);
try ctx.dir.deleteDir(test_dir_path);
}
}.impl);
}
test "Dir.rename files" {
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
// Rename on Windows can hit intermittent AccessDenied errors
// when certain conditions are true about the host system.
// For now, skip this test when the path type is UNC to avoid them.
// See https://github.com/ziglang/zig/issues/17134
if (ctx.path_type == .unc) return;
const missing_file_path = try ctx.transformPath("missing_file_name");
const something_else_path = try ctx.transformPath("something_else");
try testing.expectError(error.FileNotFound, ctx.dir.rename(missing_file_path, something_else_path));
// Renaming files
const test_file_name = try ctx.transformPath("test_file");
const renamed_test_file_name = try ctx.transformPath("test_file_renamed");
var file = try ctx.dir.createFile(test_file_name, .{ .read = true });
file.close();
try ctx.dir.rename(test_file_name, renamed_test_file_name);
// Ensure the file was renamed
try testing.expectError(error.FileNotFound, ctx.dir.openFile(test_file_name, .{}));
file = try ctx.dir.openFile(renamed_test_file_name, .{});
file.close();
// Rename to self succeeds
try ctx.dir.rename(renamed_test_file_name, renamed_test_file_name);
// Rename to existing file succeeds
const existing_file_path = try ctx.transformPath("existing_file");
var existing_file = try ctx.dir.createFile(existing_file_path, .{ .read = true });
existing_file.close();
try ctx.dir.rename(renamed_test_file_name, existing_file_path);
try testing.expectError(error.FileNotFound, ctx.dir.openFile(renamed_test_file_name, .{}));
file = try ctx.dir.openFile(existing_file_path, .{});
file.close();
}
}.impl);
}
test "Dir.rename directories" {
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
// Rename on Windows can hit intermittent AccessDenied errors
// when certain conditions are true about the host system.
// For now, skip this test when the path type is UNC to avoid them.
// See https://github.com/ziglang/zig/issues/17134
if (ctx.path_type == .unc) return;
const test_dir_path = try ctx.transformPath("test_dir");
const test_dir_renamed_path = try ctx.transformPath("test_dir_renamed");
// Renaming directories
try ctx.dir.makeDir(test_dir_path);
try ctx.dir.rename(test_dir_path, test_dir_renamed_path);
// Ensure the directory was renamed
try testing.expectError(error.FileNotFound, ctx.dir.openDir(test_dir_path, .{}));
var dir = try ctx.dir.openDir(test_dir_renamed_path, .{});
// Put a file in the directory
var file = try dir.createFile("test_file", .{ .read = true });
file.close();
dir.close();
const test_dir_renamed_again_path = try ctx.transformPath("test_dir_renamed_again");
try ctx.dir.rename(test_dir_renamed_path, test_dir_renamed_again_path);
// Ensure the directory was renamed and the file still exists in it
try testing.expectError(error.FileNotFound, ctx.dir.openDir(test_dir_renamed_path, .{}));
dir = try ctx.dir.openDir(test_dir_renamed_again_path, .{});
file = try dir.openFile("test_file", .{});
file.close();
dir.close();
}
}.impl);
}
test "Dir.rename directory onto empty dir" {
// TODO: Fix on Windows, see https://github.com/ziglang/zig/issues/6364
if (native_os == .windows) return error.SkipZigTest;
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const test_dir_path = try ctx.transformPath("test_dir");
const target_dir_path = try ctx.transformPath("target_dir_path");
try ctx.dir.makeDir(test_dir_path);
try ctx.dir.makeDir(target_dir_path);
try ctx.dir.rename(test_dir_path, target_dir_path);
// Ensure the directory was renamed
try testing.expectError(error.FileNotFound, ctx.dir.openDir(test_dir_path, .{}));
var dir = try ctx.dir.openDir(target_dir_path, .{});
dir.close();
}
}.impl);
}
test "Dir.rename directory onto non-empty dir" {
// TODO: Fix on Windows, see https://github.com/ziglang/zig/issues/6364
if (native_os == .windows) return error.SkipZigTest;
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const test_dir_path = try ctx.transformPath("test_dir");
const target_dir_path = try ctx.transformPath("target_dir_path");
try ctx.dir.makeDir(test_dir_path);
var target_dir = try ctx.dir.makeOpenPath(target_dir_path, .{});
var file = try target_dir.createFile("test_file", .{ .read = true });
file.close();
target_dir.close();
// Rename should fail with PathAlreadyExists if target_dir is non-empty
try testing.expectError(error.PathAlreadyExists, ctx.dir.rename(test_dir_path, target_dir_path));
// Ensure the directory was not renamed
var dir = try ctx.dir.openDir(test_dir_path, .{});
dir.close();
}
}.impl);
}
test "Dir.rename file <-> dir" {
// TODO: Fix on Windows, see https://github.com/ziglang/zig/issues/6364
if (native_os == .windows) return error.SkipZigTest;
try testWithAllSupportedPathTypes(struct {
fn impl(ctx: *TestContext) !void {
const test_file_path = try ctx.transformPath("test_file");
const test_dir_path = try ctx.transformPath("test_dir");
var file = try ctx.dir.createFile(test_file_path, .{ .read = true });
file.close();
try ctx.dir.makeDir(test_dir_path);
try testing.expectError(error.IsDir, ctx.dir.rename(test_file_path, test_dir_path));
try testing.expectError(error.NotDir, ctx.dir.rename(test_dir_path, test_file_path));
}
}.impl);
}
test "rename" {
var tmp_dir1 = tmpDir(.{});
defer tmp_dir1.cleanup();
var tmp_dir2 = tmpDir(.{});
defer tmp_dir2.cleanup();
// Renaming files
const test_file_name = "test_file";
const renamed_test_file_name = "test_file_renamed";
var file = try tmp_dir1.dir.createFile(test_file_name, .{ .read = true });
file.close();
try fs.rename(tmp_dir1.dir, test_file_name, tmp_dir2.dir, renamed_test_file_name);
// ensure the file was renamed
try testing.expectError(error.FileNotFound, tmp_dir1.dir.openFile(test_file_name, .{}));
file = try tmp_dir2.dir.openFile(renamed_test_file_name, .{});
file.close();
}
test "renameAbsolute" {
if (native_os == .wasi) return error.SkipZigTest;
var tmp_dir = tmpDir(.{});
defer tmp_dir.cleanup();
// Get base abs path
var arena = ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const allocator = arena.allocator();
const base_path = blk: {
const relative_path = try fs.path.join(allocator, &.{ ".zig-cache", "tmp", tmp_dir.sub_path[0..] });
break :blk try fs.realpathAlloc(allocator, relative_path);
};
try testing.expectError(error.FileNotFound, fs.renameAbsolute(
try fs.path.join(allocator, &.{ base_path, "missing_file_name" }),
try fs.path.join(allocator, &.{ base_path, "something_else" }),