From 29175d07ce1cdad494f5039242083c45feccc7c8 Mon Sep 17 00:00:00 2001 From: torque Date: Fri, 4 Aug 2023 00:14:40 -0700 Subject: [PATCH] command: add a method for creating owned interfaces This allocates the interface with its own arena allocator, allowing it to live beyond its stack lifetime. This enables some useful patterns for composing a CLI from multiple functions or files. This is actually probably the preferred method over `create_parser` in most circumstances. --- source/command.zig | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/source/command.zig b/source/command.zig index 2e6ff61..800656c 100644 --- a/source/command.zig +++ b/source/command.zig @@ -101,6 +101,31 @@ pub fn CommandBuilder(comptime UserContext: type) type { }; } + pub fn create_interface( + comptime self: @This(), + comptime callback: self.CallbackSignature(), + allocator: std.mem.Allocator, + context: UserContextType, + ) !ParserInterface { + var arena = try allocator.create(std.heap.ArenaAllocator); + arena.* = std.heap.ArenaAllocator.init(allocator); + const arena_alloc = arena.allocator(); + + var this_parser = try arena_alloc.create(Parser(self, callback)); + this_parser.* = .{ + .arena = arena, + .allocator = arena_alloc, + .subcommands = std.hash_map.StringHashMap(ParserInterface).init(arena_alloc), + .help_builder = help.HelpBuilder(self).init(arena_alloc), + }; + + if (UserContextType == void) { + return this_parser.interface(); + } else { + return this_parser.interface(context); + } + } + pub fn set_help_flag( comptime self: *@This(), comptime tags: ShortLongPair,