Skip to content

Commit 5b535df

Browse files
authored
Merge pull request #16 from katyukha/fix-topic-group
[FIX] Fix display of subcommands grouped by topic.
2 parents 08708fe + 1bd60db commit 5b535df

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

source/commandr/help.d

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ module commandr.help;
22

33
import commandr.program;
44
import commandr.option;
5-
import std.algorithm : filter, map, any, chunkBy;
5+
import std.algorithm : filter, map, any, chunkBy, sort;
66
import std.array : join, array;
77
import std.conv : to;
88
import std.stdio : writefln, writeln, write;
@@ -160,7 +160,19 @@ struct HelpPrinter {
160160
}
161161

162162
private void printSubcommands(Command[string] commands) {
163-
auto grouped = commands.values.chunkBy!(a => a.topic).array;
163+
auto grouped = commands.values
164+
.sort!((a, b) {
165+
// Note, when we used chunkBy, it is expected that range
166+
// is already sorted by the key, thus before grouping,
167+
// we have to sort by topic first.
168+
// And then by name for better output
169+
// (because associative array do not preserver order).
170+
if (a.topic == b.topic)
171+
return a.name < b.name;
172+
return a.topic < b.topic;
173+
})
174+
.chunkBy!(a => a.topic)
175+
.array;
164176

165177
if (grouped.length == 1 && grouped[0][0] is null) {
166178
foreach(key, command; commands) {

source/commandr/program.d

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,9 @@ public class Command {
252252
throw new InvalidProgramException("cannot have sub-commands and non-required argument");
253253
}
254254

255+
// TODO: may be update only if command do not have topic yet,
256+
// or only when _topicStart is set.
257+
// Because otherwise, topic set on command is overwritten here.
255258
command._topic = this._topicStart;
256259
command._parent = this;
257260
_commands[command.name] = command;
@@ -847,8 +850,13 @@ unittest {
847850
.topic("z")
848851
.topicGroup("general purpose")
849852
.add(new Command("b", "desc"))
853+
.add(new Command("c", "desc"))
854+
.topicGroup("other")
855+
.add(new Command("d", "desc"))
850856
;
851857

852858
assert(p.topic == "z");
853859
assert(p.commands["b"].topic == "general purpose");
860+
assert(p.commands["c"].topic == "general purpose");
861+
assert(p.commands["d"].topic == "other");
854862
}

0 commit comments

Comments
 (0)