/** * 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"); }
/** * Return Leading Command String. * * @param command the node to determine the path to. * @return a <code>String</code> of the executable class and command names leading to the given * command. Will never return null. */ public String getLeadingCommandString(CliCommand command) { List<String> names = new ArrayList<String>(); while (command != null) { command = command.getParent(); if (command != null) names.add(command.getCommandName()); } StringBuilder sb = new StringBuilder(cliBase.getExecutableName()); int size = names.size(); for (int j = size - 1; j >= 0; j--) sb.append(" " + names.get(j)); return sb.toString(); }
/** * Handle Configuration file. * * <p>The method will attempt to obtain the properties file from the reserved configuration switch * if it is enabled. The application wide <code>Properties</code> obtained from the <code>CliBase * </code> will be loaded with the configuration if enabled and found. * * <p>If the configuration switch is enabled and the <code>Properties</code> can not be loaded * with the given file, this method will call Help with error information. Help will exit the * application and this method will never return in this case. * * @return true if the configuration switch is enabled and the configuration was obtained. * Otherwise, false is returned. */ public boolean handleConfiguration() { boolean gotConfig = false; if (cliBase.isConfigSwitch() || !cliBase.isLogToFile()) { // if !logToFileSwitch try looking in the configuration file for configPathKey gotConfig = true; if (!commandline.hasOption(CliBase.ConfigurationPathShortCl)) { gotConfig = false; if (cliBase.isConfigSwitch() && commandline.hasOption(CliBase.HelpShortCl)) { System.err.println( "-" + CliBase.ConfigurationPathShortCl + " | --" + CliBase.ConfigurationPathLongCl + " required\n"); help(CliBase.ConfigNotFound, "Given configuration file not found"); } } if (gotConfig) { StringBuilder sb = cliBase.getInitsb(); Properties properties = cliBase.properties; String configPathKey = cliBase.getConfigPathKey(); String configPath = commandline.getOptionValue(CliBase.ConfigurationPathShortCl); StrH.ttl(sb, 1, "--", CliBase.ConfigurationPathLongCl, " = ", configPath); try { PropertiesFile.loadFile(properties, new File(configPath)); } catch (Exception e) { help(CliBase.ConfigNotFound, "Given configuration file not found"); } if (configPathKey != null) { StrH.ttl(sb, 1, configPathKey, " = ", configPath); System.setProperty(configPathKey, configPath); } } } return gotConfig; }
/** * 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; }
void parseCommandLine(String[] args) { // @formatter:on CommandLineParser parser = new DefaultParser(); try { commandline = parser.parse(options, args); } catch (AlreadySelectedException ase) { help(CliBase.InvalidCommandLine, "Already Selected: " + ase.getOption()); } catch (AmbiguousOptionException aoe) { help(CliBase.InvalidCommandLine, "Ambiguous Option: " + aoe.getMatchingOptions()); } catch (MissingArgumentException mae) { help(CliBase.InvalidCommandLine, "Missing Argument: " + mae.getOption()); } catch (MissingOptionException moe) { help(CliBase.InvalidCommandLine, "Missing Option: " + moe.getMissingOptions()); } catch (UnrecognizedOptionException uoe) { help(CliBase.InvalidCommandLine, "Unrecongnized Option: " + uoe.getOption()); } catch (Exception e) { help(CliBase.InvalidCommandLine, "Unexpected Exception: " + e.getClass().getName()); } if (commandline.hasOption(CliBase.HelpShortCl)) help(0, null); if (commandline.hasOption(CliBase.VersionShortCl)) cliBase.version(); }