lib/sandbox/src/resolve.zig

daab053ee43316e1809a84551d573ddd1e5bf3d2

 1 const std = @import("std");
 2 const sys = @import("sys");
 3 
 4 const fs_io = sys.fs.debugIo();
 5 
 6 pub fn dirPath(dir: sys.fs.Dir, buffer: []u8) ![]const u8 {
 7     if (dir.handle == std.Io.Dir.cwd().handle) {
 8         const len = try std.process.currentPath(fs_io, buffer);
 9         return buffer[0..len];
10     }
11     const len = try dir.realPath(fs_io, buffer);
12     return buffer[0..len];
13 }
14 
15 pub fn dirPathAllocZ(allocator: std.mem.Allocator, dir: sys.fs.Dir) ![:0]u8 {
16     var buffer: [std.fs.max_path_bytes]u8 = undefined;
17     const path = try dirPath(dir, &buffer);
18     return try allocator.dupeSentinel(u8, path, 0);
19 }
20 
21 test "dir path resolves the current working directory pseudo handle" {
22     var buffer: [std.fs.max_path_bytes]u8 = undefined;
23     const resolved = try dirPath(std.Io.Dir.cwd(), &buffer);
24     try std.testing.expect(std.fs.path.isAbsolute(resolved));
25 }
26 
27 test "dir path resolves real directory handles" {
28     var tmp = std.testing.tmpDir(.{});
29     defer tmp.cleanup();
30     var buffer: [std.fs.max_path_bytes]u8 = undefined;
31     const resolved = try dirPath(tmp.dir, &buffer);
32     try std.testing.expect(std.fs.path.isAbsolute(resolved));
33 }