zig/test/standalone/dirname/touch.zig
mlugg 5c8b92db7f
tests: do not require absolute paths from the build system
File arguments added to `std.Build.Step.Run` with e.g. `addFileArg` are
not necessarily passed as absolute paths. It used to be the case that
they were as a consequence of an unnecessary path conversion done by the
frontend, but this no longer happens, at least not always, so these
tests were sometimes failing when run locally. Therefore, the standalone
tests must handle cwd-relative CLI paths correctly.
2025-06-13 15:46:43 +01:00

39 lines
1,005 B
Zig

//! Creates a file at the given path, if it doesn't already exist.
//!
//! ```
//! touch <path>
//! ```
//!
//! Path must be absolute.
const std = @import("std");
pub fn main() !void {
var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const arena = arena_state.allocator();
defer arena_state.deinit();
try run(arena);
}
fn run(allocator: std.mem.Allocator) !void {
var args = try std.process.argsWithAllocator(allocator);
defer args.deinit();
_ = args.next() orelse unreachable; // skip binary name
const path = args.next() orelse {
std.log.err("missing <path> argument", .{});
return error.BadUsage;
};
const dir_path = std.fs.path.dirname(path) orelse unreachable;
const basename = std.fs.path.basename(path);
var dir = try std.fs.cwd().openDir(dir_path, .{});
defer dir.close();
_ = dir.statFile(basename) catch {
var file = try dir.createFile(basename, .{});
file.close();
};
}