Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FIX] Fix display of subcommands grouped by topic. #16

Merged
merged 1 commit into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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");
}
Loading