In zigbang, when it needs to compile the “script”, I tried to save and restore the current working directory, in between changing to the directory where to compile, using the following (with compile_dir being a Dir instance):
const old_wd = std.fs.cwd();
try compile_dir.setAsCwd();
.
.
old_wd.setAsCwd();
to my surprise this resulted in different behaviour between when the “script” needed compilation, and when not. This is because old_wd.setAsCwd(); is essentially a no-op, and old_wd.realpath() does change when compile_dir.setAsCwd(); is called.
Although I now seem to understand what is going on, I am not sure what is the best way to actually save and restore the current working directory. I don’t want to call realpath() as it may just disappear for the standard library.
For now I settled on
var outbuf: [1024]u8 = undefined;
var old_wd = try std.fs.openDirAbsolute(try std.posix.getcwd(&outbuf), .{});
defer old_wd.close();
try compile_dir.setAsCwd();
.
.
old_wd.setAsCwd();
and that works, but I would like to know if there is a better way to do this, that doesn’t involve getting a textual path representation first. E.g. using a saved inode+device of the current working directory, something which I thought the original code would do somehow.