/** * Validate the command line <code>args</code>. * * <p>This method will cause Help to be called if invalid command line <code>args</code> are * given. Help exits the application and this method will never return in this case. * * @param commandDepth the zero based depth of this command. * @return the <code>activeCommand</code> if the command line was valid and the requested command * path is down my branch. Returns null otherwise. */ public CliCommand validateCommands(int commandDepth) { String[] originalArgs = cliBase.getOriginalArgs(); // if no more nested commands, get this commands commons-cli CommandLine if (commands.size() == 0) { originalArgs = cliBase.getOriginalArgs(); if (!originalArgs[commandDepth].equals(commandName)) // -1 because CliBase holds 0th return null; commandDepth++; if (commandDepth >= originalArgs.length && hasOptions()) help(0, null); String[] myArgs = new String[originalArgs.length - commandDepth]; int j = commandDepth; for (int i = 0; i < myArgs.length; i++) myArgs[i] = originalArgs[j++]; parseCommandLine(myArgs); customInit(); return this; } String[] args = cliBase.getOriginalArgs(); if (!args[commandDepth].equals(commandName)) return null; // not my command. if (commandDepth + 1 > args.length) commandHelp(0, null); String arg = args[commandDepth + 1]; if (arg.equals("-" + CliBase.HelpShortCl) || arg.equals("--" + CliBase.HelpLongCl)) commandHelp(0, null); commandDepth++; for (Entry<String, CliCommand> entry : commands.entrySet()) { if (entry.getKey().equals(arg)) { CliCommand cliCommand = entry.getValue().validateCommands(commandDepth); if (cliCommand != null) return cliCommand; } } if (hasChildren()) commandHelp(CliBase.InvalidCommand, "Invalid command: " + arg); return null; }
/** * Leaf command help. * * <p>This method is called if the given command line <code>args</code> calls for help on a leaf * (i.e. commons-cli switches) node. * * @param exitCode the <code>System.exit</code> value to use. * @param msg Optional error message. Null if only help is to be displayed, Message is sent to * standard err before the help if not null. * @param header message to be displayed pre-help. * @param footer message to be displayed post-help. */ protected void help(int exitCode, String msg, String header, String footer) { StringBuilder command = new StringBuilder(getLeadingCommandString(this)); if (commandName != null) command.append(" " + commandName); if (exitCode != 0) { String[] args = cliBase.getOriginalArgs(); StringBuilder sb = new StringBuilder(msg == null ? "commandline: " : msg + "\ncommandline: "); for (int i = 0; i < args.length; i++) sb.append(" " + args[i]); sb.append("\n"); System.err.println(sb.toString()); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( cliBase.getMaxHelpWidth(), command.toString(), header, options, footer, true); // System.exit(exitCode); throw new RuntimeException(getClass().getSimpleName() + " Help displayed, see logs"); }