Skip to content

Commit e808676

Browse files
author
studentpiyush
committed
feat: enhanced dynamic help command with descriptions (fixes #5)
1 parent e31dfbd commit e808676

File tree

1 file changed

+53
-4
lines changed

1 file changed

+53
-4
lines changed

src/main/java/com/mycmd/commands/HelpCommand.java

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,16 @@
44
import com.mycmd.ShellContext;
55
import java.util.Map;
66

7+
/**
8+
* Enhanced HelpCommand
9+
* --------------------
10+
* Dynamically lists all available commands with their descriptions.
11+
*
12+
* Features:
13+
* - Automatically updates when new commands are added to the registry.
14+
* - Displays both command names and short descriptions.
15+
* - Supports optional usage help: "help <command>".
16+
*/
717
public class HelpCommand implements Command {
818
private final Map<String, Command> commands;
919

@@ -13,9 +23,48 @@ public HelpCommand(Map<String, Command> commands) {
1323

1424
@Override
1525
public void execute(String[] args, ShellContext context) {
16-
System.out.println("Available commands:");
17-
for (String key : commands.keySet()) {
18-
System.out.println(" - " + key);
26+
// Case 1: user asked for detailed help about one command
27+
if (args.length > 1) {
28+
String cmdName = args[1];
29+
Command cmd = commands.get(cmdName);
30+
31+
if (cmd != null) {
32+
System.out.println("\nCommand: " + cmdName);
33+
System.out.println("Description: " + cmd.description());
34+
if (cmd.usage() != null && !cmd.usage().isEmpty()) {
35+
System.out.println("Usage: " + cmd.usage());
36+
} else {
37+
System.out.println("Usage: " + cmdName + " [options]");
38+
}
39+
} else {
40+
System.out.println("No such command: " + cmdName);
41+
}
42+
return;
43+
}
44+
45+
// Case 2: user just typed 'help'
46+
System.out.println("\nMyCMD — Available Commands:\n");
47+
for (Map.Entry<String, Command> entry : commands.entrySet()) {
48+
String name = entry.getKey();
49+
Command cmd = entry.getValue();
50+
51+
String description = (cmd.description() != null && !cmd.description().isEmpty())
52+
? cmd.description()
53+
: "No description available";
54+
55+
System.out.printf(" %-12s : %s%n", name, description);
1956
}
57+
58+
System.out.println("\nType 'help <command>' for detailed info about a specific command.\n");
59+
}
60+
61+
@Override
62+
public String description() {
63+
return "Show list of available commands and their descriptions.";
64+
}
65+
66+
@Override
67+
public String usage() {
68+
return "help [command]";
2069
}
21-
}
70+
}

0 commit comments

Comments
 (0)