From 57f257fd773ecd496c71aa85e1fb1623756aebc7 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Thu, 19 May 2022 15:20:28 -0700 Subject: [PATCH] cli args support optional types --- src/Window.zig | 2 +- src/cli_args.zig | 20 +++++++++++++++++++- src/config.zig | 4 ++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/Window.zig b/src/Window.zig index 42b07148c..1799ecc32 100644 --- a/src/Window.zig +++ b/src/Window.zig @@ -150,7 +150,7 @@ pub fn create(alloc: Allocator, loop: libuv.Loop, config: *const Config) !*Windo errdefer pty.deinit(); // Create our child process - const path = (try Command.expandPath(alloc, "sh")) orelse + const path = (try Command.expandPath(alloc, config.command orelse "sh")) orelse return error.CommandNotFound; defer alloc.free(path); diff --git a/src/cli_args.zig b/src/cli_args.zig index e438aacff..0929a5c89 100644 --- a/src/cli_args.zig +++ b/src/cli_args.zig @@ -42,7 +42,13 @@ fn parseIntoField(comptime T: type, dst: *T, key: []const u8, value: ?[]const u8 inline for (info.Struct.fields) |field| { if (mem.eql(u8, field.name, key)) { @field(dst, field.name) = field: { - const Field = field.field_type; + // For optional fields, we just treat it as the child type. + // This lets optional fields default to null but get set by + // the CLI. + const Field = switch (@typeInfo(field.field_type)) { + .Optional => |opt| opt.child, + else => field.field_type, + }; const fieldInfo = @typeInfo(Field); // If the type implements a parse function, call that. @@ -137,6 +143,18 @@ test "parseIntoField: bool" { try testing.expectEqual(false, data.a); } +test "parseIntoField: optional field" { + const testing = std.testing; + + var data: struct { + a: ?bool = null, + } = .{}; + + // True + try parseIntoField(@TypeOf(data), &data, "a", "1"); + try testing.expectEqual(true, data.a.?); +} + test "parseIntoField: struct with parse func" { const testing = std.testing; diff --git a/src/config.zig b/src/config.zig index e5a6d031c..2df4b75fa 100644 --- a/src/config.zig +++ b/src/config.zig @@ -6,6 +6,10 @@ pub const Config = struct { /// Foreground color for the window. foreground: Color = .{ .r = 0xFF, .g = 0xA5, .b = 0 }, + + /// The command to run, usually a shell. If this is not an absolute path, + /// it'll be looked up in the PATH. + command: ?[]const u8 = null, }; /// Color represents a color using RGB.