public static String[] parameterArgumentNames(ParameterDescription parameterDescription) { Parameterized parameterized = parameterDescription.getParameterized(); Class cls = parameterDescription.getObject().getClass(); Field field = null; while (cls != Object.class) { try { field = cls.getDeclaredField(parameterized.getName()); } catch (NoSuchFieldException ex) { cls = cls.getSuperclass(); continue; } break; } assert field != null; ExtendedParameter extendedParameter = field.getAnnotation(ExtendedParameter.class); if (extendedParameter != null) { return extendedParameter.argumentNames(); } return new String[0]; }
private void parameterDoc(StringBuilder result, ParameterDescription parameterDescription) { result.append(" * `") .append(parameterDescription.getNames()) .append("`: "); Object def = parameterDescription.getDefault(); if (def != null) { result.append("(*Default*: `") .append(def.toString()) .append("`) "); } if (parameterDescription.getParameter().required()) { result.append("(*Required*) "); } if (parameterDescription.getParameter().password()) { result.append("(*Sensitive data* - user will be prompted on standard input) "); } result.append(parameterDescription.getDescription()) .append("\n"); }
private static void formatParameter(AnsiStoryBuilder story, ParameterDescription parameter, int indentWidth) { AnsiParagraphBuilder paragraph = story.addParagraph().setIndentWidth(indentWidth); paragraph.addSnippet(parameter.getNames()).addStyle(AnsiStyle.BOLD); if (parameter.getDefault() != null) { paragraph.addSnippet("="); paragraph.addSnippet(parameter.getDefault().toString()).addStyle(AnsiStyle.UNDERLINE); } if (parameter.getParameter().required()) { paragraph.addSnippet(" (required)"); } if (parameter.getParameter().password()) { paragraph.addSnippet(" (sensitive data - user will be prompted)"); } paragraph = story.addParagraph().setIndentWidth(indentWidth * 2); paragraph.addSnippet(parameter.getDescription()); story.addNewline(); }
public void printGenericHelp() { boolean hasRequired = false; console.info( "\nUsage: {} [options] [command] [command options]", programName); console.info("\n Options:\n"); for (ParameterDescription param : jc.getParameters()) { hasRequired = printOption(console, param) || hasRequired; } if (hasRequired) { console.info("\n * = required"); } console.info("\n Commands:\n"); for (String command : jc.getCommands().keySet()) { console.info(" {}\n\t{}", command, jc.getCommandDescription(command)); } console.info("\n Examples:"); console.info("\n # print information for create\n {} help create", programName); console.info("\n See '{} help <command>' for more information on a " + "specific command.", programName); }
private int getParameterArity(ParameterDescription param) { if (param.getParameter().arity() > 0) { return param.getParameter().arity(); } Class<?> type = param.getParameterized().getType(); if ((type == boolean.class || type == Boolean.class)) { return 0; } return 1; }
private List<ParameterDescription> getSortedParameters(JCommander jc) { List<ParameterDescription> parameters = Lists.newArrayList(jc.getParameters()); final Pattern pattern = Pattern.compile("^-*(.*)$"); Collections.sort(parameters, new Comparator<ParameterDescription>() { @Override public int compare(ParameterDescription o1, ParameterDescription o2) { String s1; Matcher matcher = pattern.matcher(o1.getParameter().names()[0]); if (matcher.matches()) { s1 = matcher.group(1); } else { throw new IllegalStateException(); } String s2; matcher = pattern.matcher(o2.getParameter().names()[0]); if (matcher.matches()) { s2 = matcher.group(1); } else { throw new IllegalStateException(); } return s1.compareTo(s2); } }); return parameters; }
private String commandCompletorCase(int depth) { JarResource completorCase = new JarResource("/hal-completor-case"); Map<String, String> bindings = new HashMap<>(); String flagNames = commander.getParameters() .stream() .map(ParameterDescription::getLongestName) .reduce("", (a, b) -> a + " " + b); String subcommandNames = subcommands.entrySet() .stream() .map(Map.Entry::getKey) .reduce("", (a, b) -> a + " " + b); bindings.put("subcommands", subcommandNames); bindings.put("flags", flagNames); bindings.put("command", getCommandName()); bindings.put("depth", depth + ""); bindings.put("next", (depth + 1) + ""); String subCases = subcommands.entrySet() .stream() .map(c -> c.getValue().commandCompletorCase(depth + 1)) .reduce("", (a, b) -> a + b); bindings.put("recurse", subCases.isEmpty() ? ":" : subCases); return completorCase.setBindings(bindings).toString(); }
private static void logHelp(JCommander jcommander) { List<ParameterDescription> parameters = jcommander.getParameters(); for (ParameterDescription parameter : parameters) { LOG.info(parameter.getLongestName() + " : " + parameter.getDescription()); } System.exit(0); }
public @NonNull Set<String> parametersOfCommand(final @NonNull String command) { requireNonNull(command); checkArgument(!command.isEmpty()); return commandsMap.get(command) .getParameters() .stream() .map(ParameterDescription::getLongestName) .collect(toSet()); }
public @NonNull Set<String> parametersOfCommandStartingWith(final @NonNull String command, final @NonNull String prefix) { requireNonNull(command); requireNonNull(prefix); checkArgument(!command.isEmpty()); return commandsMap.get(command) .getParameters() .stream() .map(ParameterDescription::getLongestName) .filter(s -> s.startsWith(prefix)) .collect(toSet()); }
@Override public Map<String, String> getArguments() { if(commander == null) commander = new JCommander(new SysInfoParams()); Map<String, String> result = new HashMap<String,String>(); List<ParameterDescription> params = commander.getParameters(); for(ParameterDescription param : params){ result.put(param.getNames(), param.getDescription()); } return result; }
public static String usage(CommonArgs serviceArgs, String commandOfInterest) { String result = null; StringBuilder helperMessage = new StringBuilder(); if (commandOfInterest == null) { // JCommander.usage is too verbose for a command with many options like // slider no short version of that is found Instead, we compose our msg by helperMessage.append("\nUsage: slider COMMAND [options]\n"); helperMessage.append("where COMMAND is one of\n"); for (String jcommand : serviceArgs.commander.getCommands().keySet()) { helperMessage.append(String.format("\t%-" + DIFF_BETWEEN_DESCIPTION_AND_COMMAND_NAME + "s%s", jcommand, serviceArgs.commander.getCommandDescription(jcommand) + "\n")); } helperMessage .append("Most commands print help when invoked without parameters"); result = helperMessage.toString(); } else { helperMessage.append("\nUsage: slider " + commandOfInterest); helperMessage.append(serviceArgs.coreAction.getMinParams() > 0 ? " <application>" : ""); helperMessage.append("\n"); for (ParameterDescription paramDesc : serviceArgs.commander.getCommands() .get(commandOfInterest).getParameters()) { String optional = paramDesc.getParameter().required() ? " (required)" : " (optional)"; String paramName = paramDesc.getParameterized().getType() == Boolean.TYPE ? paramDesc .getLongestName() : paramDesc.getLongestName() + " <" + paramDesc.getParameterized().getName() + ">"; helperMessage.append(String.format("\t%-" + DIFF_BETWEEN_DESCIPTION_AND_COMMAND_NAME + "s%s", paramName, paramDesc.getDescription() + optional + "\n")); result = helperMessage.toString(); } } return result; }
private boolean printOption(Logger console, ParameterDescription param) { boolean required = param.getParameter().required(); if (!param.getParameter().hidden()) { console.info(" {} {}\n\t{}{}", new Object[]{ required ? "*" : " ", param.getNames().trim(), param.getDescription(), formatDefault(param)}); } return required; }
private String formatDefault(ParameterDescription param) { Object defaultValue = param.getDefault(); if (defaultValue == null || param.getParameter().arity() < 1) { return ""; } return " (default: " + ((defaultValue instanceof String) ? "\"" + defaultValue + "\"" : defaultValue.toString()) + ")"; }
/** * Output details about the main parameter, if there is one. * * @param commander * @return */ @SuppressWarnings("unchecked") public static StringBuilder explainMainParameter( JCommander commander ) { StringBuilder builder = new StringBuilder(); ParameterDescription mainParameter = commander.getMainParameter(); // Output the main parameter. if (mainParameter != null) { if (mainParameter.getDescription() != null && mainParameter.getDescription().length() > 0) { builder.append("Expects: "); builder.append(mainParameter.getDescription()); builder.append("\n"); } boolean assigned = mainParameter.isAssigned(); builder.append("Specified: "); List<String> mP = (List<String>) mainParameter.getParameterized().get( mainParameter.getObject()); if (!assigned || mP.size() == 0) { builder.append("<none specified>"); } else { builder.append(String.format( "%n%s", StringUtils.join( mP, " "))); } builder.append("\n"); } return builder; }
@Override public int compare(ParameterDescription left, ParameterDescription right){ int leftOrder = getParameterOrder(left); int rightOrder = getParameterOrder(right); if(leftOrder > -1 || rightOrder > -1){ return Integer.compare(leftOrder, rightOrder); } return (left.getLongestName()).compareToIgnoreCase(right.getLongestName()); }
private int getParameterOrder(ParameterDescription parameterDescription){ Field field; try { field = Parameterized.class.getDeclaredField("m_field"); } catch(NoSuchFieldException nsfe){ throw new RuntimeException(nsfe); } Field parameterField; try { Parameterized parameterized = parameterDescription.getParameterized(); if(!field.isAccessible()){ field.setAccessible(true); } parameterField = (Field)field.get(parameterized); } catch(IllegalAccessException iae){ throw new RuntimeException(iae); } if(parameterField != null){ ParameterOrder parameterOrder = parameterField.getAnnotation(ParameterOrder.class); if(parameterOrder != null){ return parameterOrder.value(); } } return -1; }
public @NonNull Set<String> parametersOfMainCommand() { return commander.getParameters().stream().map(ParameterDescription::getLongestName).collect(toSet()); }
@Override public int run() { if (helpCommands.isEmpty()) { printGenericHelp(); } else { for (String cmd : helpCommands) { JCommander commander = jc.getCommands().get(cmd); if (commander == null) { console.error("\nUnknown command: {}\n", cmd); printGenericHelp(); return 1; } boolean hasRequired = false; console.info("\nUsage: {} [general options] {} {} [command options]", new Object[] { programName, cmd, commander.getMainParameterDescription()}); console.info("\n Description:"); console.info("\n {}", jc.getCommandDescription(cmd)); if (!commander.getParameters().isEmpty()) { console.info("\n Command options:\n"); for (ParameterDescription param : commander.getParameters()) { hasRequired = printOption(console, param) || hasRequired; } if (hasRequired) { console.info("\n * = required"); } } List<String> examples = ((Command) commander.getObjects().get(0)).getExamples(); if (examples != null) { console.info("\n Examples:"); for (String example : examples) { if (example.startsWith("#")) { // comment console.info("\n {}", example); } else { console.info(" {} {} {}", new Object[] {programName, cmd, example}); } } } // add an extra newline in case there are more commands console.info(""); } } return 0; }
@Override public int compare(ParameterDescription arg0, ParameterDescription arg1) { return arg0.getNames().compareTo(arg1.getNames()); }
@Override public void validate(String name, String value, ParameterDescription pd) throws ParameterException { validate(name, value); }