1717
1818@ Command (name = "help" , desc = "List every command" )
1919public class HelpCommand extends AbstractCommand {
20+
2021 private int longestNameLength ;
22+ private CliContext context ;
2123 private Io io ;
2224
25+ @ Override
26+ public String [] getUsages () {
27+ return new String [] {"[category]" };
28+ }
29+
2330 @ Override
2431 public void getOptions (Options options ) {}
2532
2633 @ Override
2734 public void run (CliContext context , CommandLine args ) {
2835 Application app = context .getApp ();
36+ this .context = context ;
2937 this .io = context .getIo ();
3038
39+ String category = handleArgs (args );
40+ if (category == null ) {
41+ return ;
42+ }
43+
3144 StringBuilder sb = new StringBuilder ();
32- sb .append ("TMC commands:\n " );
45+ if (category .equals ("" )) {
46+ sb .append ("TMC commands:\n " );
47+ } else {
48+ sb .append ("TMC commands in " ).append (category ).append (":\n " );
49+ }
3350
34- List <String > commandStrings = getCommandStrings ();
51+ List <String > commandStrings = getCommandStrings (category );
3552 Collections .sort (commandStrings );
3653 for (String commandString : commandStrings ) {
3754 sb .append (commandString ).append ("\n " );
@@ -40,15 +57,43 @@ public void run(CliContext context, CommandLine args) {
4057 app .printHelp (sb .toString ());
4158 }
4259
43- private List <String > getCommandStrings () {
60+ private String handleArgs (CommandLine args ) {
61+ String [] stringArguments = args .getArgs ();
62+ if (stringArguments .length > 1 ) {
63+ io .errorln ("Too many arguments." );
64+ printUsage (context );
65+ return null ;
66+ }
67+ String category = "" ;
68+ if (stringArguments .length == 1 ) {
69+ category = stringArguments [0 ];
70+ }
71+ if (category .equals ("all" )) {
72+ return category ;
73+ }
74+ Set <String > helpCategories = CommandFactory .getCommandCategories ();
75+ if (!helpCategories .contains (category )) {
76+ io .errorln ("Unknown command category \" " + category + "\" ." );
77+ return null ;
78+ }
79+ return category ;
80+ }
81+
82+ private List <String > getCommandStrings (String category ) {
4483 List <String > strings = new ArrayList <>();
45- List <Class <Command >> commands = CommandFactory .getCommands ();
84+ List <Class <Command >> commands ;
85+ if (category .equals ("all" )) {
86+ commands = CommandFactory .getCommands ();
87+ } else {
88+ commands = CommandFactory .getCategoryCommands (category );
89+ }
4690
4791 longestNameLength = longestName (commands );
4892 for (Class <Command > commandClass : commands ) {
4993 Command command = CommandFactory .getCommand (commandClass );
5094 strings .add (createCommandString (command ));
5195 }
96+ longestNameLength = Math .max (longestNameLength , 8 );
5297 return strings ;
5398 }
5499
0 commit comments