diff options
| author | matu3ba <matu3ba@users.noreply.github.com> | 2022-04-28 17:37:30 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-04-28 18:37:30 +0300 |
| commit | 7f13f5cd5f5a518638b15d7225eae2d88ec1efb5 (patch) | |
| tree | 2b63e2c8ed35d36671c5a8380e2ea290b4b5395b /lib/std/testing.zig | |
| parent | 8e3add8736be683b450c2754bedb064811baed0e (diff) | |
| download | zig-7f13f5cd5f5a518638b15d7225eae2d88ec1efb5.tar.gz zig-7f13f5cd5f5a518638b15d7225eae2d88ec1efb5.zip | |
std.testing: add writeZigFile for TmpDir
* remove need for manual string concatenation for building binaries in test blocks
* include small program snippet to show how to get binary path with subslicing
Diffstat (limited to 'lib/std/testing.zig')
| -rw-r--r-- | lib/std/testing.zig | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/lib/std/testing.zig b/lib/std/testing.zig index 004e2d0fa7..df2d6c7a43 100644 --- a/lib/std/testing.zig +++ b/lib/std/testing.zig @@ -374,6 +374,43 @@ pub const TmpDir = struct { self.parent_dir.close(); self.* = undefined; } + + /// Writes program string as zig file into tmp directory + /// Caller owns memory + /// + /// ``` + /// const progstr = "pub fn main() void {}\n"; + /// var it = try std.process.argsWithAllocator(std.testing.allocator); + /// defer it.deinit(); // no-op unless WASI or Windows + /// const testargs = try std.testing.getTestArgs(&it); + /// var tmp = std.testing.tmpDir(.{ .no_follow = true }); // ie zig-cache/tmp/8DLgoSEqz593PAEE + /// defer tmp.cleanup(); + /// const zigfile_path = try tmp.writeZigFile(std.testing.allocator, progstr, "bruh"); + /// defer std.testing.allocator.free(zigfile_path); + /// const binary = zigfile_path[0 .. zigfile_path.len - 4]; // '.zig' is 4 characters + /// try std.testing.buildExe(testargs.zigexec, zigfile_path, binary); + /// ``` + pub fn writeZigFile( + self: *TmpDir, + alloc: std.mem.Allocator, + progstr: []const u8, + filename: []const u8, + ) ![]const u8 { + const tmpdir_path = try self.getFullPath(alloc); + defer alloc.free(tmpdir_path); + const suffix_zig = ".zig"; + const zigfile_path = try std.mem.concat(alloc, u8, &[_][]const u8{ + tmpdir_path, + std.fs.path.sep_str, + filename, + suffix_zig, + }); + errdefer alloc.free(zigfile_path); + const zigfile = try std.mem.concat(alloc, u8, &[_][]const u8{ filename, suffix_zig }); + defer alloc.free(zigfile); + try self.dir.writeFile(zigfile, progstr); + return zigfile_path; + } }; fn getCwdOrWasiPreopen() std.fs.Dir { |
