An interface for all the commands that can be run from a shell.
| 33 | * An interface for all the commands that can be run from a shell. |
| 34 | */ |
| 35 | public interface Command extends Comparable<Command>, Closeable { |
| 36 | |
| 37 | /** |
| 38 | * Gets the command name as input from the shell. |
| 39 | * |
| 40 | * @return the command name |
| 41 | */ |
| 42 | String getCommandName(); |
| 43 | |
| 44 | @Override |
| 45 | default int compareTo(Command that) { |
| 46 | return this.getCommandName().compareTo(that.getCommandName()); |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * @return the supported {@link Options} of the command |
| 51 | */ |
| 52 | default Options getOptions() { |
| 53 | return new Options(); |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * If a command has sub-commands, the first argument should be the sub-command's name, |
| 58 | * all arguments and options will be parsed for the sub-command. |
| 59 | * |
| 60 | * @return whether this command has sub-commands |
| 61 | */ |
| 62 | default boolean hasSubCommand() { |
| 63 | return Optional.ofNullable(getSubCommands()).filter(subs -> !subs.isEmpty()).isPresent(); |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * @return a map from sub-command names to sub-command instances |
| 68 | */ |
| 69 | default Map<String, Command> getSubCommands() { |
| 70 | return Collections.emptyMap(); |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Parses and validates the arguments. |
| 75 | * |
| 76 | * @param args the arguments for the command, excluding the command name |
| 77 | * @return the parsed command line object |
| 78 | * @throws IllegalArgumentException when arguments are not valid |
| 79 | */ |
| 80 | default CommandLine parseAndValidateArgs(String... args) throws IllegalArgumentException { |
| 81 | CommandLine cmdline; |
| 82 | Options opts = getOptions(); |
| 83 | CommandLineParser parser = new DefaultParser(); |
| 84 | try { |
| 85 | cmdline = parser.parse(opts, args); |
| 86 | } catch (ParseException e) { |
| 87 | throw new IllegalArgumentException( |
| 88 | String.format("Failed to parse args for %s: %s", getCommandName(), e.getMessage()), e); |
| 89 | } |
| 90 | validateArgs(cmdline); |
| 91 | return cmdline; |
| 92 | } |
no outgoing calls
no test coverage detected