From 4104f78cba322da7210124aa3b8dc82e1ac5f545 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 27 Oct 2023 15:57:20 -0700 Subject: [PATCH] cli: handle "-e" as the command to execute --- src/cli/args.zig | 5 +++++ src/config/Config.zig | 30 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/cli/args.zig b/src/cli/args.zig index fcb4c039c..eb91c43a8 100644 --- a/src/cli/args.zig +++ b/src/cli/args.zig @@ -64,6 +64,11 @@ pub fn parse(comptime T: type, alloc: Allocator, dst: *T, iter: anytype) !void { }; while (iter.next()) |arg| { + // Do manual parsing if we have a hook for it. + if (@hasDecl(T, "parseManuallyHook")) { + if (!try dst.parseManuallyHook(arena_alloc, arg, iter)) return; + } + if (mem.startsWith(u8, arg, "--")) { var key: []const u8 = arg[2..]; const value: ?[]const u8 = value: { diff --git a/src/config/Config.zig b/src/config/Config.zig index a527cd70e..0bd1410ef 100644 --- a/src/config/Config.zig +++ b/src/config/Config.zig @@ -1145,6 +1145,36 @@ pub fn finalize(self: *Config) !void { if (self.@"window-height" > 0) self.@"window-height" = @max(4, self.@"window-height"); } +/// Callback for src/cli/args.zig to allow us to handle special cases +/// like `--help` or `-e`. Returns "false" if the CLI parsing should halt. +pub fn parseManuallyHook(self: *Config, alloc: Allocator, arg: []const u8, iter: anytype) !bool { + // If it isn't "-e" then we just continue parsing normally. + if (!std.mem.eql(u8, arg, "-e")) return true; + + // The first value is the command to run. + if (iter.next()) |command| { + self.command = try alloc.dupe(u8, command); + } else { + try self._errors.add(alloc, .{ + .message = try std.fmt.allocPrintZ( + alloc, + "missing command after -e", + .{}, + ), + }); + + return false; + } + + // All further arguments are parameters + while (iter.next()) |param| { + try self.@"command-arg".parseCLI(alloc, param); + } + + // Do not continue, we consumed everything. + return false; +} + /// Create a shallow copy of this config. This will share all the memory /// allocated with the previous config but will have a new arena for /// any changes or new allocations. The config should have `deinit`