command: preserve subcommand definition order

This was as simple as switching to an order preserving hashmap. This
lets the user decide which order their subcommands should be presented
in.
This commit is contained in:
torque 2023-11-08 22:56:11 -08:00
parent 768a81e2bd
commit 645ef24a4a
Signed by: torque
SSH Key Fingerprint: SHA256:nCrXefBNo6EbjNSQhv0nXmEg/VuNq3sMF5b8zETw3Tk
3 changed files with 7 additions and 9 deletions

View File

@ -167,7 +167,7 @@ pub fn CommandBuilder(comptime UserContext: type) type {
return Parser(self, callback){ return Parser(self, callback){
.arena = arena, .arena = arena,
.allocator = arena_alloc, .allocator = arena_alloc,
.subcommands = std.hash_map.StringHashMap(ParserInterface).init(arena_alloc), .subcommands = parser.CommandMap.init(arena_alloc),
.help_builder = help.HelpBuilder(self).init(arena_alloc), .help_builder = help.HelpBuilder(self).init(arena_alloc),
}; };
} }
@ -188,7 +188,7 @@ pub fn CommandBuilder(comptime UserContext: type) type {
this_parser.* = .{ this_parser.* = .{
.arena = arena, .arena = arena,
.allocator = arena_alloc, .allocator = arena_alloc,
.subcommands = std.hash_map.StringHashMap(ParserInterface).init(arena_alloc), .subcommands = parser.CommandMap.init(arena_alloc),
.help_builder = help.HelpBuilder(self).init(arena_alloc), .help_builder = help.HelpBuilder(self).init(arena_alloc),
}; };

View File

@ -360,11 +360,10 @@ pub fn HelpBuilder(comptime command: anytype) type {
defer pairs.deinit(); defer pairs.deinit();
var just: usize = 0; var just: usize = 0;
var iter = subcommands.keyIterator(); for (subcommands.keys()) |key| {
while (iter.next()) |key| {
const pair: AlignablePair = .{ const pair: AlignablePair = .{
.left = key.*, .left = key,
.right = subcommands.get(key.*).?.describe(), .right = subcommands.get(key).?.describe(),
}; };
if (pair.left.len > just) just = pair.left.len; if (pair.left.len > just) just = pair.left.len;
try pairs.append(pair); try pairs.append(pair);

View File

@ -73,7 +73,7 @@ pub const ParserInterface = struct {
} }
}; };
pub const CommandMap = std.hash_map.StringHashMap(ParserInterface); pub const CommandMap = std.StringArrayHashMap(ParserInterface);
// the parser is generated by the bind method of the CommandBuilder, so we can // the parser is generated by the bind method of the CommandBuilder, so we can
// be extremely type-sloppy here, which simplifies the signature. // be extremely type-sloppy here, which simplifies the signature.
@ -144,8 +144,7 @@ pub fn Parser(comptime command: anytype, comptime callback: anytype) type {
} }
pub fn deinitTree(self: @This()) void { pub fn deinitTree(self: @This()) void {
var iterator = self.subcommands.valueIterator(); for (self.subcommands.values()) |subcommand| {
while (iterator.next()) |subcommand| {
subcommand.deinitTree(); subcommand.deinitTree();
} }
self.deinit(); self.deinit();