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:
parent
86342bcd1f
commit
29175d07ce
@ -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,
|
||||
|
Loading…
x
Reference in New Issue
Block a user