Skip to content

Instantly share code, notes, and snippets.

@slimsag
Created June 1, 2021 20:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slimsag/84cb56c7114796bcef4ed9773a20d8a0 to your computer and use it in GitHub Desktop.
Save slimsag/84cb56c7114796bcef4ed9773a20d8a0 to your computer and use it in GitHub Desktop.
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const process = std.process;
const fs = std.fs;
const ChildProcess = std.ChildProcess;
var a: *std.mem.Allocator = undefined;
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
a = &arena.allocator;
const stdout = std.io.getStdOut().writer();
var build_args = std.ArrayList([]const u8).init(a);
defer build_args.deinit();
try build_args.appendSlice(&[_][]const u8{
"/bin/ls",
"-rtl",
"/tmp",
});
const res = try exec("/tmp", build_args.items);
try stdout.print("{s}\n", .{res.stdout});
// const res = exec([]const []const u8 .{ "ls", "-l" }, "/tmp");
// try stdout.print("------\n", .{});
}
fn printCmd(cwd: []const u8, argv: []const []const u8) void {
std.debug.warn("cd {s} && ", .{cwd});
for (argv) |arg| {
std.debug.warn("{s} ", .{arg});
}
std.debug.warn("\n", .{});
}
fn exec(cwd: []const u8, argv: []const []const u8) !ChildProcess.ExecResult {
const max_output_size = 100 * 1024 * 1024;
// const result = ChildProcess.exec(a, argv, cwd, null, max_output_size) catch |err| {
const result = ChildProcess.exec(.{
.allocator = a,
.argv = argv,
.cwd = cwd,
.env_map = null,
.max_output_bytes = max_output_size,
}) catch |err| {
std.debug.warn("The following command failed:\n", .{});
printCmd(cwd, argv);
return err;
};
switch (result.term) {
.Exited => |code| {
if (code != 0) {
std.debug.warn("The following command exited with error code {any}:\n", .{code});
printCmd(cwd, argv);
std.debug.warn("stderr:\n{s}\n", .{result.stderr});
return error.CommandFailed;
}
},
else => {
std.debug.warn("The following command terminated unexpectedly:\n", .{});
printCmd(cwd, argv);
std.debug.warn("stderr:\n{s}\n", .{result.stderr});
return error.CommandFailed;
},
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment