com.beust.jcommander.ParameterDescription Java Examples

The following examples show how to use com.beust.jcommander.ParameterDescription. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Help.java    From parquet-mr with Apache License 2.0 6 votes vote down vote up
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));
  }

  jc.getCommands().keySet().stream().filter(s -> !s.equals("help")).findFirst().ifPresent(command -> {
    console.info("\n  Examples:");
    console.info("\n    # print information for {}\n    {} help {}",
      command, programName, command);
    console.info("\n  See '{} help <command>' for more information on a " +
      "specific command.", programName);
  });
}
 
Example #2
Source File: AbstractCmd.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
/**
 * Extract flags info from the JCommander instance and append those to the provided StringBuilder instance.
 *
 * @param jCommander respective JCommander instance.
 * @param sb         StringBuilder instance.
 */
private static void appendFlagsInfo(JCommander jCommander, StringBuilder sb) {
    List<ParameterDescription> params = jCommander.getParameters().stream()
            .filter(param -> !param.getParameter().hidden()).collect(Collectors.toList());

    // if no hidden flag is there, return from here
    if (params.isEmpty()) {
        return;
    }

    int maxLength = params.stream().mapToInt(param -> param.getNames().length()).max().orElse(15);

    sb.append("Flags:\n");
    params.stream().filter(param -> !param.getParameter().hidden()).forEach(param -> {
        sb.append(String.format("%2s%-" + String.valueOf(maxLength + LOGS_PADDING) + "s", "", param.getNames()));
        sb.append(param.getDescription());
        sb.append(" (default: ");
        sb.append(param.getDefault());
        sb.append(")\n");
    });
    sb.append("\n");
}
 
Example #3
Source File: Options.java    From terracotta-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a {@code Map} containing only the parameters relevant to {@code Node} object with longest parameter name
 * as the key and user-specified-value as the value.
 *
 * @param jCommander jCommander instance
 */
private void extractTopologyOptions(CustomJCommander jCommander) {
  Collection<String> userSpecifiedOptions = jCommander.getUserSpecifiedOptions();
  Predicate<ParameterDescription> isSpecified =
      pd -> Arrays.stream(pd.getNames().split(","))
          .map(String::trim)
          .anyMatch(userSpecifiedOptions::contains);

  jCommander.getParameters()
      .stream()
      .filter(isSpecified)
      .filter(pd -> {
        String longestName = pd.getLongestName();
        return !longestName.equals(addDashDash(LICENSE_FILE))
            && !longestName.equals(addDashDash(CONFIG_FILE))
            && !longestName.equals(addDashDash(REPAIR_MODE))
            && !longestName.equals(addDashDash(AUTO_ACTIVATE))
            && !longestName.equals(addDashDash(NODE_CONFIG_DIR));
      })
      .forEach(pd -> paramValueMap.put(Setting.fromName(ConsoleParamsUtils.stripDashDash(pd.getLongestName())), pd.getParameterized().get(this).toString()));
}
 
Example #4
Source File: ShellCommand.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Populates the completions and documentation based on the JCommander.
 *
 * The input data is copied, so changing the jcommander after creation of the
 * JCommanderCompletor doesn't change the completions.
 */
JCommanderCompletor(JCommander jcommander) {
  ImmutableTable.Builder<String, String, ParamDoc> builder = new ImmutableTable.Builder<>();

  // Go over all the commands
  for (Entry<String, JCommander> entry : jcommander.getCommands().entrySet()) {
    String command = entry.getKey();
    JCommander subCommander = entry.getValue();

    // Add the "main" parameters documentation
    builder.put(command, "", ParamDoc.create(subCommander.getMainParameter()));

    // For each command - go over the parameters (arguments / flags)
    for (ParameterDescription parameter : subCommander.getParameters()) {
      ParamDoc paramDoc = ParamDoc.create(parameter);

      // For each parameter - go over all the "flag" names of that parameter (e.g., -o and
      // --output being aliases of the same parameter) and populate each one
      Arrays.stream(parameter.getParameter().names())
          .forEach(flag -> builder.put(command, flag, paramDoc));
    }
  }
  commandFlagDocs = builder.build();
}
 
Example #5
Source File: NestableCommand.java    From halyard with Apache License 2.0 6 votes vote down vote up
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(linkify(parameterDescription.getDescription())).append("\n");
}
 
Example #6
Source File: NestableCommand.java    From halyard with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #7
Source File: NestableCommand.java    From halyard with Apache License 2.0 6 votes vote down vote up
private String commandCompletorCase(int depth) {
  StringReplaceJarResource completorCase = new StringReplaceJarResource("/hal-completor-case");
  Map<String, Object> 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();
}
 
Example #8
Source File: ShellCommand.java    From nomulus with Apache License 2.0 6 votes vote down vote up
static ParamDoc create(@Nullable ParameterDescription parameter) {
  if (parameter == null) {
    return create("[None]", ImmutableList.of());
  }
  String type = parameter.getParameterized().getGenericType().toString();
  Class<?> clazz = parameter.getParameterized().getType();
  ImmutableList<String> options = ImmutableList.of();
  if (clazz.isEnum()) {
    options =
        Arrays.stream(clazz.getEnumConstants())
            .map(Object::toString)
            .collect(toImmutableList());
    type = options.stream().collect(Collectors.joining(", "));
  }
  if (type.startsWith("class ")) {
    type = type.substring(6);
  }
  return create(
      String.format(
          "%s\n  (%s)",
          parameter.getDescription(),
          type),
      options);
}
 
Example #9
Source File: Help.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
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()) + ")";
}
 
Example #10
Source File: Help.java    From kite with Apache License 2.0 5 votes vote down vote up
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()) + ")";
}
 
Example #11
Source File: ExplainCommand.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Output details about the main parameter, if there is one.
 *
 * @return the explanation for the main parameter
 */
@SuppressWarnings("unchecked")
public static StringBuilder explainMainParameter(final JCommander commander) {
  final StringBuilder builder = new StringBuilder();

  final ParameterDescription mainParameter = commander.getMainParameterValue();

  // 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");
    }

    final boolean assigned = mainParameter.isAssigned();
    builder.append("Specified: ");
    final 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;
}
 
Example #12
Source File: ParameterOrderComparator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
@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());
}
 
Example #13
Source File: JCommanderWrapper.java    From jadx with Apache License 2.0 5 votes vote down vote up
public void overrideProvided(T obj) {
	List<ParameterDescription> fieldsParams = jc.getParameters();
	List<ParameterDescription> parameters = new ArrayList<>(1 + fieldsParams.size());
	parameters.add(jc.getMainParameterValue());
	parameters.addAll(fieldsParams);
	for (ParameterDescription parameter : parameters) {
		if (parameter.isAssigned()) {
			// copy assigned field value to obj
			Parameterized parameterized = parameter.getParameterized();
			Object val = parameterized.get(parameter.getObject());
			parameterized.set(obj, val);
		}
	}
}
 
Example #14
Source File: Help.java    From kite with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #15
Source File: Help.java    From kite with Apache License 2.0 5 votes vote down vote up
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()) + ")";
}
 
Example #16
Source File: Help.java    From kite with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #17
Source File: CatalogCrawler.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public int compare(ParameterDescription p0, ParameterDescription p1) {
  int index0 = orderedParamNames.indexOf(p0.getLongestName());
  int index1 = orderedParamNames.indexOf(p1.getLongestName());
  assert index0 >= 0 : "Unexpected parameter name: " + p0.getLongestName();
  assert index1 >= 0 : "Unexpected parameter name: " + p1.getLongestName();

  return Integer.compare(index0, index1);
}
 
Example #18
Source File: Help.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #19
Source File: CmdGenerateDocument.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private void generateDocument(StringBuilder sb, String module, JCommander obj) {
    sb.append("------------\n\n");
    sb.append("# ").append(module).append("\n\n");
    sb.append("### Usage\n\n");
    sb.append("`$").append(module).append("`\n\n");
    sb.append("------------\n\n");
    sb.append(baseJcommander.getCommandDescription(module)).append("\n");
    sb.append("\n\n```bdocs-tab:example_shell\n")
            .append("$ pulsar-admin ").append(module).append(" subcommand")
            .append("\n```");
    sb.append("\n\n");
    CmdBase cmdObj = (CmdBase) obj.getObjects().get(0);
    for (String s : cmdObj.jcommander.getCommands().keySet()) {
        sb.append("* `").append(s).append("`\n");
    }
    cmdObj.jcommander.getCommands().forEach((subK, subV) -> {
        sb.append("\n\n## <em>").append(subK).append("</em>\n\n");
        sb.append(cmdObj.jcommander.getCommandDescription(subK)).append("\n\n");
        sb.append("### Usage\n\n");
        sb.append("------------\n\n\n");
        sb.append("```bdocs-tab:example_shell\n$ pulsar-admin ").append(module).append(" ")
                .append(subK).append(" options").append("\n```\n\n");
        List<ParameterDescription> options = cmdObj.jcommander.getCommands().get(subK).getParameters();
        if (options.size() > 0) {
            sb.append("Options\n\n\n");
            sb.append("|Flag|Description|Default|\n");
            sb.append("|---|---|---|\n");
        }
        options.forEach((option) ->
            sb.append("| `").append(option.getNames())
                    .append("` | ").append(option.getDescription().replace("\n", " "))
                    .append("|").append(option.getDefault()).append("|\n")
        );
    });
    System.out.println(sb.toString());
}
 
Example #20
Source File: Nccopy.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public int compare(ParameterDescription p0, ParameterDescription p1) {
  int index0 = orderedParamNames.indexOf(p0.getLongestName());
  int index1 = orderedParamNames.indexOf(p1.getLongestName());
  assert index0 >= 0 : "Unexpected parameter name: " + p0.getLongestName();
  assert index1 >= 0 : "Unexpected parameter name: " + p1.getLongestName();

  return Integer.compare(index0, index1);
}
 
Example #21
Source File: CFPointWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public int compare(ParameterDescription p0, ParameterDescription p1) {
  int index0 = orderedParamNames.indexOf(p0.getLongestName());
  int index1 = orderedParamNames.indexOf(p1.getLongestName());
  assert index0 >= 0 : "Unexpected parameter name: " + p0.getLongestName();
  assert index1 >= 0 : "Unexpected parameter name: " + p1.getLongestName();

  return Integer.compare(index0, index1);
}
 
Example #22
Source File: CFPointWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public int compare(ParameterDescription p0, ParameterDescription p1) {
  int index0 = orderedParamNames.indexOf(p0.getLongestName());
  int index1 = orderedParamNames.indexOf(p1.getLongestName());
  assert index0 >= 0 : "Unexpected parameter name: " + p0.getLongestName();
  assert index1 >= 0 : "Unexpected parameter name: " + p1.getLongestName();

  return Integer.compare(index0, index1);
}
 
Example #23
Source File: Help.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example #24
Source File: AbstractCommand.java    From apiman-cli with Apache License 2.0 4 votes vote down vote up
private StringBuilder usage(JCommander parent, StringBuilder sb) {
    JCommander jc = getCommand(parent);
    StringBuilder intermediary = new StringBuilder("Usage: " + getCommandChain(parent));
    // Handle arguments
    List<ParameterDescription> parameters = jc.getParameters();
    parameters.sort((e1, e2) -> {
        int mandatory = -Boolean.compare(e1.getParameter().required(), e2.getParameter().required());
        return mandatory != 0 ? mandatory : e1.getLongestName().compareTo(e2.getLongestName());
    });

    // Build parameter list
    for (ParameterDescription param : parameters) {
        // Optional open braces
        if (!param.getParameter().required()) {
            intermediary.append("[");
        } else {
            intermediary.append("(");
        }

        intermediary.append(param.getNames());

        // Optional close braces
        if (!param.getParameter().required()) {
            intermediary.append("]");
        } else {
            intermediary.append(")");
        }

        intermediary.append(" ");
    }

    // Doing it this way in case we decide to have width limits.
    if (intermediary.length() > 0) {
        sb.append(intermediary);
    }

    // Handle sub-commands
    if (!jc.getCommands().isEmpty()) {
        sb.append("<command> [<args>]");
        sb.append(LINE_SEPARATOR).append(LINE_SEPARATOR);
        sb.append("The following commands are available:");
        sb.append(LINE_SEPARATOR).append(LINE_SEPARATOR);

        // Each command
        jc.getCommands().forEach((key, value) -> {
            sb.append("   ");
            sb.append(key).append(": ");
            sb.append(jc.getCommandDescription(key));
            sb.append(LINE_SEPARATOR);
        });
    }

    // Handle arguments
    if (!jc.getParameters().isEmpty()) {
        sb.append(LINE_SEPARATOR);
        sb.append("The following arguments are available:");
        sb.append(LINE_SEPARATOR).append(LINE_SEPARATOR);

        parameters.forEach(param -> {
            // Foo: Description
            sb.append("   ");
            sb.append(param.getNames() + ": ");
            sb.append(param.getDescription());
            // If there is a default set and it's not a boolean
            if (param.getDefault() != null &&
                    !(param.getDefault() instanceof Boolean)) {
                sb.append(" [default: ");
                sb.append(param.getDefault());
                sb.append("]");
            }
            sb.append(LINE_SEPARATOR);
        });
    }

    return sb;
}
 
Example #25
Source File: HelpCommand.java    From Scribengin with GNU Affero General Public License v3.0 4 votes vote down vote up
private String printSubCommand(Map.Entry<String, Command> entry) throws Exception {

    StringBuilder builder = new StringBuilder();
    String commandName = entry.getKey();
    builder.append("" + commandName + ":\n");
    builder.append(repeat(" ", indent) + wordWrap(entry.getValue().getDescription(), indent*1))
        .append("\n\n");
    for (Entry<String, Class<? extends SubCommand>> subCommands : entry.getValue().getSubcommands()
        .entrySet()) {
      builder.append(repeat(" ",indent)).append("* " + subCommands.getKey());
      builder.append("\n").append(repeat(" ", indent*2)+
          wordWrap(subCommands.getValue().newInstance().getDescription(), indent*2)).append("\n\n");
      JCommander jcommander = new JCommander(subCommands.getValue().newInstance());
      List<ParameterDescription> params = jcommander.getParameters();
      if (params.size() > 0) {
        Collections.sort(params, new ParameterComparator());
        TabularFormater formatter = null;
        for (ParameterDescription parameterDescription : params) {
          int length = 0;
          //builder.append(repeat(" ", indent*3) + parameterDescription.getNames() + ": ");
          length = parameterDescription.getNames().length();
          int thisargsindent = argIndent - length;
          if(thisargsindent <= 0){
            thisargsindent = 1;
          }
          //builder.append(wordWrap(repeat(" ", thisargsindent)+parameterDescription.getDescription(),argIndent+8))
          //    .append("\n");
          formatter = new TabularFormater("Option", "Description", "Default Value");
          try{
            formatter.addRow(parameterDescription.getNames().trim(),
                          parameterDescription.getDescription().trim(),
                          parameterDescription.getDefault());
          } catch (Exception e){
            formatter.addRow(parameterDescription.getNames().trim(),
                parameterDescription.getDescription().trim(),
                "");
          }
          
        }
        if(formatter != null){
          builder.append(indent(formatter.getFormatText(), indent*4));
        }
        builder.append("\n");
      }
    }
    builder.append("\n");
    return builder.toString();
  }
 
Example #26
Source File: HelpCommand.java    From Scribengin with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public int compare(ParameterDescription arg0, ParameterDescription arg1) {
  return arg0.getNames().compareTo(arg1.getNames());
}
 
Example #27
Source File: AbstractCommand.java    From apiman-cli with Apache License 2.0 4 votes vote down vote up
private boolean noArgsSet(JCommander jc) {
    return jc.getParameters().stream().noneMatch(ParameterDescription::isAssigned);
}