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.
This commit is contained in:
torque 2023-08-04 00:14:40 -07:00
parent 86342bcd1f
commit 29175d07ce
Signed by: torque
SSH Key Fingerprint: SHA256:nCrXefBNo6EbjNSQhv0nXmEg/VuNq3sMF5b8zETw3Tk

View File

@ -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( pub fn set_help_flag(
comptime self: *@This(), comptime self: *@This(),
comptime tags: ShortLongPair, comptime tags: ShortLongPair,