Skip to content

Commit

Permalink
Merge pull request #16 from katyukha/fix-topic-group
Browse files Browse the repository at this point in the history
[FIX] Fix display of subcommands grouped by topic.
  • Loading branch information
robik authored Aug 21, 2024
2 parents 08708fe + 1bd60db commit 5b535df
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
16 changes: 14 additions & 2 deletions source/commandr/help.d
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module commandr.help;

import commandr.program;
import commandr.option;
import std.algorithm : filter, map, any, chunkBy;
import std.algorithm : filter, map, any, chunkBy, sort;
import std.array : join, array;
import std.conv : to;
import std.stdio : writefln, writeln, write;
Expand Down Expand Up @@ -160,7 +160,19 @@ struct HelpPrinter {
}

private void printSubcommands(Command[string] commands) {
auto grouped = commands.values.chunkBy!(a => a.topic).array;
auto grouped = commands.values
.sort!((a, b) {
// Note, when we used chunkBy, it is expected that range
// is already sorted by the key, thus before grouping,
// we have to sort by topic first.
// And then by name for better output
// (because associative array do not preserver order).
if (a.topic == b.topic)
return a.name < b.name;
return a.topic < b.topic;
})
.chunkBy!(a => a.topic)
.array;

if (grouped.length == 1 && grouped[0][0] is null) {
foreach(key, command; commands) {
Expand Down
8 changes: 8 additions & 0 deletions source/commandr/program.d
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,9 @@ public class Command {
throw new InvalidProgramException("cannot have sub-commands and non-required argument");
}

// TODO: may be update only if command do not have topic yet,
// or only when _topicStart is set.
// Because otherwise, topic set on command is overwritten here.
command._topic = this._topicStart;
command._parent = this;
_commands[command.name] = command;
Expand Down Expand Up @@ -847,8 +850,13 @@ unittest {
.topic("z")
.topicGroup("general purpose")
.add(new Command("b", "desc"))
.add(new Command("c", "desc"))
.topicGroup("other")
.add(new Command("d", "desc"))
;

assert(p.topic == "z");
assert(p.commands["b"].topic == "general purpose");
assert(p.commands["c"].topic == "general purpose");
assert(p.commands["d"].topic == "other");
}

0 comments on commit 5b535df

Please sign in to comment.