1// Test relative paths through POSIX APIS. These tests have to change the cwd, so
2// they shouldn't be Zig unit tests.
3
4const builtin = @import("builtin");
5
6const std = @import("std");
7const Io = std.Io;
8
9pub fn main(init: std.process.Init) !void {
10 if (builtin.target.os.tag == .wasi) return; // Can link, but can't change into tmpDir
11
12 const io = init.io;
13
14 const args = try init.minimal.args.toSlice(init.arena.allocator());
15 const tmp_dir_path = args[1];
16
17 var tmp_dir = try Io.Dir.cwd().openDir(io, tmp_dir_path, .{});
18 defer tmp_dir.close(io);
19
20 // Want to test relative paths, so cd into the tmpdir for these tests
21 try std.process.setCurrentDir(io, tmp_dir);
22
23 try test_link(io, tmp_dir);
24}
25
26fn test_link(io: Io, tmp_dir: Io.Dir) !void {
27 switch (builtin.target.os.tag) {
28 .linux, .illumos => {},
29 else => return,
30 }
31
32 const target_name = "link-target";
33 const link_name = "newlink";
34
35 try tmp_dir.writeFile(io, .{ .sub_path = target_name, .data = "example" });
36
37 // Test 1: create the relative link from inside tmp_dir
38 try Io.Dir.hardLink(.cwd(), target_name, .cwd(), link_name, io, .{});
39
40 // Verify
41 const efd = try tmp_dir.openFile(io, target_name, .{});
42 defer efd.close(io);
43
44 const nfd = try tmp_dir.openFile(io, link_name, .{});
45 defer nfd.close(io);
46
47 {
48 const e_stat = try efd.stat(io);
49 const n_stat = try nfd.stat(io);
50 try std.testing.expectEqual(e_stat.inode, n_stat.inode);
51 try std.testing.expectEqual(2, n_stat.nlink);
52 }
53
54 // Test 2: Remove the link and see the stats update
55 try Io.Dir.cwd().deleteFile(io, link_name);
56 {
57 const e_stat = try efd.stat(io);
58 try std.testing.expectEqual(1, e_stat.nlink);
59 }
60}