Java Code Examples for com.beust.jcommander.JCommander#getParameters()

The following examples show how to use com.beust.jcommander.JCommander#getParameters() . 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: 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 2
Source File: ExplainCommand.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(final OperationParams inputParams) {

  final CommandLineOperationParams params = (CommandLineOperationParams) inputParams;

  final StringBuilder builder = new StringBuilder();

  // Sort first
  String nextCommand = "geowave";
  JCommander commander = params.getCommander();
  while (commander != null) {
    if ((commander.getParameters() != null) && (commander.getParameters().size() > 0)) {
      builder.append("Command: ");
      builder.append(nextCommand);
      builder.append(" [options]");
      if (commander.getParsedCommand() != null) {
        builder.append(" <subcommand> ...");
      }
      builder.append("\n\n");
      builder.append(explainCommander(commander));
      builder.append("\n");
    } else if (commander.getMainParameter() != null) {
      builder.append("Command: ");
      builder.append(nextCommand);
      if (commander.getParsedCommand() != null) {
        builder.append(" <subcommand> ...");
      }
      builder.append("\n\n");
      builder.append(explainMainParameter(commander));
      builder.append("\n");
    }
    nextCommand = commander.getParsedCommand();
    commander = commander.getCommands().get(nextCommand);
  }

  params.getConsole().println(builder.toString().trim());
}
 
Example 3
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 4
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 5
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();
  }