diff --git a/src/main.zig b/src/main.zig index 3fc4eef..2ae4128 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,50 +1,61 @@ -const std = @import("std"); -const Linenoise = @import("linenoise").Linenoise; +const stdout = std.io.getStdOut().writer(); fn clear() !void { - const stdout = std.io.getStdOut().writer(); try stdout.print("\u{001b}[H\u{001b}[J", .{}); } -fn getPrompt() ![]const u8 { +fn getPrompt(allocator: Allocator) ![]const u8 { const script = @embedFile("./get_prompt.bash"); const result = try std.process.Child.run(.{ - .allocator = std.heap.page_allocator, + .allocator = allocator, .argv = &[_][]const u8{ "bash", "-i", "-c", script }, }); + allocator.free(result.stderr); return result.stdout; } +fn runCommand(command: []const u8, allocator: Allocator) !u8 { + var argv_array_list = ArrayList([]const u8).init(allocator); + defer argv_array_list.deinit(); + + var tokens = tokenizeAny(u8, command, " "); + while (tokens.next()) |token| { + try argv_array_list.append(token); + } + + var child = std.process.Child.init(argv_array_list.items, allocator); + const result = child.spawnAndWait() catch |err| { + std.log.debug("Error forking", .{}); + return err; + }; + return result.Exited; +} + pub fn main() !void { try clear(); - const allocator = std.heap.page_allocator; + var gpa = std.heap.GeneralPurposeAllocator(.{}).init; + defer _ = gpa.deinit(); + defer _ = gpa.detectLeaks(); + + const allocator = gpa.allocator(); + var ln = Linenoise.init(allocator); defer ln.deinit(); - const p = try getPrompt(); + const p = try getPrompt(allocator); + defer allocator.free(p); while (try ln.linenoise(p)) |input| { defer allocator.free(input); std.debug.print("input: {s}\n", .{input}); try ln.history.add(input); + _ = try runCommand(input, allocator); } } -test "simple test" { - var list = std.ArrayList(i32).init(std.testing.allocator); - defer list.deinit(); // Try commenting this out and see if zig detects the memory leak! - try list.append(42); - try std.testing.expectEqual(@as(i32, 42), list.pop()); -} - -test "fuzz example" { - const Context = struct { - fn testOne(context: @This(), input: []const u8) anyerror!void { - _ = context; - // Try passing `--fuzz` to `zig build test` and see if it manages to fail this test case! - try std.testing.expect(!std.mem.eql(u8, "canyoufindme", input)); - } - }; - try std.testing.fuzz(Context{}, Context.testOne, .{}); -} +const std = @import("std"); +const tokenizeAny = std.mem.tokenizeAny; +const Allocator = std.mem.Allocator; +const ArrayList = std.ArrayList; +const Linenoise = @import("linenoise").Linenoise;