parser: add interface method for retrieving a child interface by name

The main value of this method is that it allows runtime access to the
help description of the subcommand. This could allow implementation of
a help flag that takes the name of a subcommand to print help for or
something. Anyway, it's probably useful.
This commit is contained in:
torque 2023-08-04 00:18:38 -07:00
parent d091de5686
commit 883218cdca
Signed by: torque
SSH Key Fingerprint: SHA256:nCrXefBNo6EbjNSQhv0nXmEg/VuNq3sMF5b8zETw3Tk

View File

@ -12,6 +12,7 @@ pub const ParserInterface = struct {
execute: *const fn (parser: *anyopaque, context: *anyopaque) anyerror!void,
parse: *const fn (parser: *anyopaque, context: *anyopaque, name: []const u8, args: [][:0]u8, env: std.process.EnvMap) anyerror!void,
finish: *const fn (parser: *anyopaque, context: *anyopaque) anyerror!void,
getChild: *const fn (parser: *anyopaque, name: []const u8) ?ParserInterface,
describe: *const fn () []const u8,
deinit: *const fn (parser: *anyopaque) void,
deinitTree: *const fn (parser: *anyopaque) void,
@ -29,6 +30,7 @@ pub const ParserInterface = struct {
.execute = ParserType.wrap_execute,
.parse = ParserType.wrap_parse,
.finish = ParserType.wrap_finish,
.getChild = ParserType.wrap_getChild,
.describe = ParserType.describe,
.deinit = ParserType.wrap_deinit,
.deinitTree = ParserType.wrap_deinitTree,
@ -48,6 +50,10 @@ pub const ParserInterface = struct {
return try self.methods.finish(self.parser, self.context);
}
pub fn getChild(self: @This(), name: []const u8) ?ParserInterface {
return self.methods.getChild(self.parser, name);
}
pub fn describe(self: @This()) []const u8 {
return self.methods.describe();
}
@ -147,6 +153,11 @@ pub fn Parser(comptime command: anytype, comptime callback: anytype) type {
return try self.finish(context);
}
fn wrap_getChild(parser: *anyopaque, name: []const u8) ?ParserInterface {
const self = cast_interface_parser(parser);
return self.getChild(name);
}
fn wrap_deinit(parser: *anyopaque) void {
const self = cast_interface_parser(parser);
self.deinit();
@ -200,6 +211,10 @@ pub fn Parser(comptime command: anytype, comptime callback: anytype) type {
self.deinit();
}
pub fn getChild(self: @This(), name: []const u8) ?ParserInterface {
return self.subcommands.get(name);
}
pub fn execute(self: *@This(), context: UserContext) anyerror!void {
const args = try std.process.argsAlloc(self.allocator);
var env = try std.process.getEnvMap(self.allocator);