@Test
  public void testOptionsWithDefaultValue() {
    CLI cli = CLIConfigurator.define(CommandForDefaultValueTest.class);

    assertThat(cli.getOptions()).hasSize(1);
    assertThat(find(cli.getOptions(), "option").getDefaultValue()).isEqualTo("bar");
    assertThat(find(cli.getOptions(), "option").getName()).isEqualTo("option");
  }
  @Test
  public void testOptionsWithDescription() {
    CLI cli = CLIConfigurator.define(CommandForDescriptionTest.class);

    assertThat(cli.getOptions()).hasSize(1);
    assertThat(find(cli.getOptions(), "option").getDescription())
        .isEqualTo("This option is awesome");
  }
Example #3
0
  private void generateBuildSystem() throws MojoExecutionException {
    try {
      packageDirectory.mkdirs();
      new File(packageDirectory, "m4").mkdirs();
      targetSrcDir = new File(packageDirectory, "src");
      targetSrcDir.mkdirs();

      if (customPackageDirectory != null && customPackageDirectory.isDirectory()) {
        FileUtils.copyDirectoryStructureIfModified(customPackageDirectory, packageDirectory);
      }

      if (generatedNativeSourceDirectory != null && generatedNativeSourceDirectory.isDirectory()) {
        FileUtils.copyDirectoryStructureIfModified(generatedNativeSourceDirectory, targetSrcDir);
      }

      copyTemplateResource("readme.md", false);
      copyTemplateResource("configure.ac", true);
      copyTemplateResource("Makefile.am", true);
      copyTemplateResource("m4/custom.m4", false);
      copyTemplateResource("m4/jni.m4", false);
      copyTemplateResource("m4/osx-universal.m4", false);

      // To support windows based builds..
      String tool = windowsBuildTool.toLowerCase().trim();
      if ("detect".equals(tool)) {
        copyTemplateResource("vs2008.vcproj", true);
        copyTemplateResource("vs2010.vcxproj", true);
      } else if ("msbuild".equals(tool)) {
        copyTemplateResource("vs2010.vcxproj", true);
      } else if ("vcbuild".equals(tool)) {
        copyTemplateResource("vs2008.vcproj", true);
      } else if ("none".equals(tool)) {
      } else {
        throw new MojoExecutionException(
            "Invalid setting for windowsBuildTool: " + windowsBuildTool);
      }

      File autogen = new File(packageDirectory, "autogen.sh");
      File configure = new File(packageDirectory, "configure");
      if (!autogen.exists()) {
        copyTemplateResource("autogen.sh", false);
        cli.setExecutable(autogen);
      }
      if (!skipAutogen) {
        if ((!configure.exists() && !CLI.IS_WINDOWS) || forceAutogen) {
          try {
            cli.system(packageDirectory, new String[] {"./autogen.sh"}, autogenArgs);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }

    } catch (Exception e) {
      throw new MojoExecutionException("Native build system generation failed: " + e, e);
    }
  }
  @Test
  public void testInjectionOfString() throws CLIException {
    HelloClI command = new HelloClI();
    CLI cli = CLIConfigurator.define(HelloClI.class);
    CommandLine evaluatedCLI = cli.parse(Arrays.asList("--name", "vert.x"));
    CLIConfigurator.inject(evaluatedCLI, command);

    assertThat(command.run()).isEqualToIgnoringCase("Hello vert.x");
    assertThat(command.name).isEqualToIgnoringCase("vert.x");
  }
 @Test
 public void testOptionsParsedAsList() {
   CLI command = CLIConfigurator.define(CommandForParsedAsList.class);
   assertThat(command.getOptions()).hasSize(1);
   assertThat(((TypedOption) find(command.getOptions(), "option")).getListSeparator())
       .isEqualTo(":");
   assertThat(find(command.getOptions(), "option").isMultiValued()).isTrue();
   assertThat(((TypedOption) find(command.getOptions(), "option")).getType())
       .isEqualTo(String.class);
 }
Example #6
0
 public void command(CLI cli) {
   Scope scope = Scope.ROOT_SCOPE;
   cli.getOut().println("Root scope: ");
   for (Map.Entry<String, List<Declaration>> scopeEntry : scope) {
     cli.getOut().println(scopeEntry.getKey() + ": ");
     for (Declaration decl : scopeEntry.getValue()) {
       cli.getOut()
           .println("        " + decl.getKind() + " " + decl.getName() + " (" + decl + ")");
     }
   }
 }
Example #7
0
 @Test
 public void specifyingADefaultValueForAnOption() throws Exception {
   cli =
       new CLI() {
         {
           option("-b").takingArgument("SIZE").ofType(int.class).defaultingTo(1024);
         }
       };
   cli.parse();
   assertEquals(1024, cli.get("-b"));
 }
 @Test
 public void testUsage() {
   CLI command = CLIConfigurator.define(HelloClI.class);
   StringBuilder builder = new StringBuilder();
   command.usage(builder);
   assertThat(builder)
       .containsIgnoringCase("Usage: hello -n <name>")
       .containsIgnoringCase("A command saying hello.")
       .containsIgnoringCase("A simple cli to wish you a good day. Pass your name with `--name`")
       .containsIgnoringCase(" -n,--name <name>   your name");
 }
Example #9
0
 @Test
 public void usingSimpleOptionSwitches() throws ParsingException {
   cli =
       new CLI() {
         {
           flag("-x").describedAs("Turns debugging on");
         }
       };
   cli.parse("-x");
   assertTrue(cli.has("-x"));
 }
Example #10
0
 @Test
 public void usingACustomOptionType() throws Exception {
   cli =
       new CLI() {
         {
           coerceType(BigDecimal.class).using(new BigDecimalCoercer());
           option("--size VALUE").ofType(BigDecimal.class);
         }
       };
   cli.parse("--size", "1000.00");
   assertEquals(new BigDecimal("1000.00"), cli.get("--size"));
 }
Example #11
0
 @Test
 public void definingAnOptionWithAnAliasForm() throws Exception {
   cli =
       new CLI() {
         {
           option("-x").alias("--debug");
         }
       };
   cli.parse("--debug");
   assertTrue(cli.has("-x"));
   assertTrue(cli.has("--debug"));
 }
Example #12
0
  private CLI runCliWithInput(String... inputLines) {
    StringBuilder builder = new StringBuilder();
    for (String line : inputLines) {
      builder.append(line).append(System.getProperty("line.separator"));
    }

    ByteArrayInputStream in = new ByteArrayInputStream(builder.toString().getBytes());
    CLI cli = new CLI(in, testOut);
    cli.startEventLoop();

    return cli;
  }
Example #13
0
 @Test
 public void specifyingTheTypeOfAnOptionArgument() throws Exception {
   cli =
       new CLI() {
         {
           option("-b").takingArgument("SIZE").ofType(int.class);
         }
       };
   cli.parse("-b", "1024");
   int blockSize = cli.<Integer>get("-b");
   assertEquals(1024, blockSize);
 }
Example #14
0
 @Test
 public void specifyingAnOptionInLiteralForm() throws Exception {
   cli =
       new CLI() {
         {
           option("-h", "--host HOSTNAME", "Hostname to bind to");
         }
       };
   cli.parse("--host", "0.0.0.0");
   assertTrue(cli.has("-h"));
   assertTrue(cli.has("--host"));
   assertEquals("0.0.0.0", cli.get("-h"));
 }
Example #15
0
 @Test
 public void usingBuiltInCoercers() throws Exception {
   cli =
       new CLI() {
         {
           option("-c").takingArgument("CLASSNAME").ofType(Class.class);
           operand("file").ofType(File.class);
         }
       };
   cli.parse("-c", "java.lang.String", "/path/to/file");
   assertEquals(String.class, cli.get("-c"));
   assertEquals(new File("/path/to/file"), cli.get("file"));
 }
Example #16
0
  @Test
  public void definingAnOptionThatExpectsAnArgument() throws Exception {
    cli =
        new CLI() {
          {
            option("-b").takingArgument("SIZE");
          }
        };
    cli.parse("-b", "1024");

    assertTrue(cli.has("-b"));
    assertEquals("1024", cli.get("-b"));
  }
Example #17
0
  @Test
  public void specifyingTheTypeOfAPositionalArgument() throws ParsingException {
    cli =
        new CLI() {
          {
            operand("input").ofType(File.class);
          }
        };
    cli.parse("/path/to/input");

    File inputFile = cli.get("input");
    assertEquals("/path/to/input", inputFile.getAbsolutePath());
  }
Example #18
0
  @Test
  public void usingPositionalArguments() throws Exception {
    cli =
        new CLI() {
          {
            operand("input").describedAs("The input file");
            operand("output").describedAs("The output file");
          }
        };
    cli.parse("input", "output");

    assertEquals("input", cli.get("input"));
    assertEquals("output", cli.get("output"));
  }
  @Test
  public void testTypeExtraction() {
    CLI command = CLIConfigurator.define(CommandForTypeExtractTest.class);

    assertThat(command.getOptions()).hasSize(6);
    TypedOption model = (TypedOption) find(command.getOptions(), "list");
    assertThat(model.getType()).isEqualTo(String.class);
    assertThat(model.isMultiValued()).isTrue();

    model = (TypedOption) find(command.getOptions(), "set");
    assertThat(model.getType()).isEqualTo(Character.class);
    assertThat(model.isMultiValued()).isTrue();

    model = (TypedOption) find(command.getOptions(), "collection");
    assertThat(model.getType()).isEqualTo(Integer.class);
    assertThat(model.isMultiValued()).isTrue();

    model = (TypedOption) find(command.getOptions(), "tree");
    assertThat(model.getType()).isEqualTo(String.class);
    assertThat(model.isMultiValued()).isTrue();

    model = (TypedOption) find(command.getOptions(), "al");
    assertThat(model.getType()).isEqualTo(String.class);
    assertThat(model.isMultiValued()).isTrue();

    model = (TypedOption) find(command.getOptions(), "array");
    assertThat(model.getType()).isEqualTo(Integer.TYPE);
    assertThat(model.isMultiValued()).isTrue();
  }
Example #20
0
 private static Arguments getArgs(final String[] args) throws Exception {
   try {
     return CLI.getArguments(args);
   } catch (final Exception e) {
     throw new Exception("Encountered an error when parsing arguments", e);
   }
 }
  @Test
  public void testHelloCLIFromClass() {
    CLI command = CLIConfigurator.define(HelloClI.class);

    assertThat(command.getOptions()).hasSize(1);
    TypedOption option = (TypedOption) find(command.getOptions(), "name");
    assertThat(option.getLongName()).isEqualToIgnoringCase("name");
    assertThat(option.getShortName()).isEqualToIgnoringCase("n");
    assertThat(option.getType()).isEqualTo(String.class);
    assertThat(option.getArgName()).isEqualTo("name");
    assertThat(option.getDescription()).isEqualToIgnoringCase("your name");
    assertThat(option.getDefaultValue()).isNull();
    assertThat(option.acceptValue()).isTrue();
    assertThat(option.isMultiValued()).isFalse();
    assertThat(option.isRequired()).isTrue();
  }
Example #22
0
  @Test
  public void retrievingArgumentsInATypeSafeWay() throws ParsingException {
    cli = new CLI();
    ArgumentSpec<Boolean> verbose = cli.option("-v").ofType(Boolean.class);
    ArgumentSpec<Integer> size =
        cli.option("--block-size").takingArgument("SIZE").ofType(int.class).defaultingTo(1024);
    OperandSpec<File> input = cli.operand("input").ofType(File.class);
    Args args = cli.parse("-v", "--block-size", "2048", "/path/to/input");

    File inputFile = input.get(args);
    assertEquals("/path/to/input", inputFile.getAbsolutePath());
    boolean verboseFlag = verbose.get(args);
    assertEquals(true, verboseFlag);
    int blockSize = size.get(args);
    assertEquals(2048, blockSize);
  }
 @Override
 public <T> T getArgumentValue(String name) {
   Argument arg = cli.getArgument(name);
   if (arg == null) {
     return null;
   }
   return getArgumentValue(arg.getIndex());
 }
Example #24
0
  public static void main(String args[]) throws Exception {

    CLI cli = new CLI();
    CommandLine cl = cli.getCommandLine(args);

    if (!cl.hasOption(CLI.O_ACTION)) {
      cli.usage(new ParseException("missing required option " + CLI.O_ACTION), true);
    }

    String action = cl.getOptionValue(CLI.O_ACTION);
    if ("dump".equals(action)) {
      doDump(cl);
    } else if ("check".equals(action)) {
      doCheck(cl);
    } else {
      cli.usage(new ParseException("invalid option " + action), true);
    }
  }
 /**
  * Checks whether or not the user has passed a "help" option and is asking for help.
  *
  * @return {@code true} if the user command line has enabled a "Help" option, {@link false}
  *     otherwise.
  */
 @Override
 public boolean isAskingForHelp() {
   for (Option option : cli.getOptions()) {
     if (option.isHelp() && isSeenInCommandLine(option)) {
       return true;
     }
   }
   return false;
 }
Example #26
0
 @Test
 public void retrievingExtraArguments() throws ParsingException {
   cli =
       new CLI() {
         {
           operand("input");
         }
       };
   Args args = cli.parse("input", "output", "encoding");
   assertEquals(asList("output", "encoding"), args.others());
 }
Example #27
0
 @Test
 public void detectingAnUnrecognizedOption() throws Exception {
   cli = new CLI();
   try {
     cli.parse("--whatever");
     fail("Expected exception " + UnrecognizedOptionException.class.getName());
   } catch (UnrecognizedOptionException expected) {
     assertEquals("--whatever", expected.getOption());
     assertThat(expected.getMessage(), containsString("whatever"));
   }
 }
 @Override
 public boolean isFlagEnabled(String name) {
   Option option = cli.getOption(name);
   if (option == null) {
     throw new IllegalArgumentException("Cannot find the option '" + name + "'");
   }
   if (option.isFlag()) {
     return optionsSeenInCommandLine.contains(option);
   } else {
     throw new IllegalStateException(
         "Cannot retrieve the flag value on a non-flag option (" + name + ")");
   }
 }
 @Override
 @SuppressWarnings("unchecked")
 public <T> T getOptionValue(String name) {
   Option option = cli.getOption(name);
   if (option == null) {
     return null;
   }
   if (option instanceof TypedOption) {
     return getValue((TypedOption<T>) option);
   } else {
     return (T) getRawValueForOption(option);
   }
 }
 @Override
 @SuppressWarnings("unchecked")
 public <T> T getArgumentValue(int index) {
   Argument arg = cli.getArgument(index);
   if (arg == null) {
     return null;
   }
   if (arg instanceof TypedArgument) {
     return create(getRawValueForArgument(arg), (TypedArgument<T>) arg);
   } else {
     return (T) getRawValueForArgument(arg);
   }
 }