From 22f24043755ed320eff8a121aa1b80ede3b3a37f Mon Sep 17 00:00:00 2001 From: Mathias Magnusson Date: Mon, 4 Aug 2025 17:23:44 +0200 Subject: improve cli a tiny bit --- src/main.zig | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 2e89029..205c452 100644 --- a/src/main.zig +++ b/src/main.zig @@ -18,25 +18,44 @@ pub fn main() !u8 { var args = std.process.args(); _ = args.next(); + const Action = enum { + run, + compile, + }; + const action = (if (args.next()) |act| std.meta.stringToEnum(Action, act) else null) orelse { + std.debug.print("Invalid action. Supply `run` or `compile`.", .{}); + return 1; + }; + + const dir = switch (action) { + .run => blk: { + const dir = try std.fmt.allocPrint(allocator, "/tmp/huginn-build-{}", .{std.crypto.random.int(u32)}); + try std.fs.makeDirAbsolute(dir); + break :blk dir; + }, + .compile => ".", + }; + const in_path = args.next(); const in_file = if (in_path) |path| try std.fs.cwd().openFile(path, .{}) else std.io.getStdIn(); - const out_path = args.next(); - const out_file = if (out_path) |path| - try std.fs.cwd().createFile(path, .{ .mode = 0o777 }) - else - std.io.getStdOut(); - - const run = if (args.next()) |arg| std.mem.eql(u8, arg, "run") else false; + const out_name = if (in_path) |p| blk: { + if (!std.mem.endsWith(u8, p, ".hgn")) { + std.debug.print("Invalid input file extension. Must be `.hgn`.", .{}); + return 1; + } + break :blk p[0 .. p.len - 4]; + } else "a.out"; + const out_path = try std.fmt.allocPrint(allocator, "{s}/{s}", .{ dir, out_name }); + const out_file = try std.fs.cwd().createFile(out_path, .{ .mode = 0o777 }); const source = try in_file.readToEndAlloc( allocator, 640 * 1024, // ought to be enough for anyone ); - defer allocator.free(source); var lexer: Lexer = .{ .source = source }; const ast = parse.file(allocator, &lexer) catch |err| { @@ -58,8 +77,8 @@ pub fn main() !u8 { return 1; }; try out_file.writer().writeAll(elf); - std.debug.print(blue ++ "running program:" ++ normal ++ "\n", .{}); - if (run) { + if (action == .run) { + std.debug.print(blue ++ "running program:" ++ normal ++ "\n", .{}); out_file.close(); const err = std.process.execv( @@ -67,7 +86,7 @@ pub fn main() !u8 { if (target.cpu.arch == .riscv64 and target.os.tag == .linux) &.{out_path} else - &.{ "qemu-riscv64", out_path.? }, + &.{ "qemu-riscv64", out_path }, ); std.debug.print(red ++ "{}\n" ++ normal ++ "{any}\n", .{ err, @errorReturnTrace() }); return 1; -- cgit v1.2.3