picocli.CommandLine.Command Java Examples

The following examples show how to use picocli.CommandLine.Command. 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: SubcommandTests.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetUnmatchedOptionsAllowedAsOptionParameters_AfterSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    commandLine.addSubcommand("main", createNestedCommand());
    assertTrue(commandLine.isUnmatchedOptionsAllowedAsOptionParameters());
    commandLine.setUnmatchedOptionsAllowedAsOptionParameters(false);
    assertFalse(commandLine.isUnmatchedOptionsAllowedAsOptionParameters());

    int childCount = 0;
    int grandChildCount = 0;
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added before IS impacted", false, sub.isUnmatchedOptionsAllowedAsOptionParameters());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subsubcommand added before IS impacted", false, sub.isUnmatchedOptionsAllowedAsOptionParameters());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #2
Source File: SubcommandTests.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetNegatableOptionTransformer_BeforeSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    assertEquals(CommandLine.RegexTransformer.class, commandLine.getNegatableOptionTransformer().getClass());
    CustomNegatableOptionTransformer newValue = new CustomNegatableOptionTransformer();
    commandLine.setNegatableOptionTransformer(newValue);
    assertEquals(newValue, commandLine.getNegatableOptionTransformer());

    int childCount = 0;
    int grandChildCount = 0;
    commandLine.addSubcommand("main", createNestedCommand());
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added afterwards is not impacted", CommandLine.RegexTransformer.class, sub.getNegatableOptionTransformer().getClass());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subcommand added afterwards is not impacted", CommandLine.RegexTransformer.class, subsub.getNegatableOptionTransformer().getClass());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #3
Source File: EndOfOptionsDelimiterTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testShowEndOfOptionsDelimiterInUsageHelpSystemProperties() {
    @Command(name = "myapp", mixinStandardHelpOptions = true,
            showEndOfOptionsDelimiterInUsageHelp = true, description = "Example command.")
    class MyApp {
        @Parameters(description = "A file.") File file;
    }

    System.setProperty("picocli.endofoptions.description", "End of options -- rock!");

    String actual = new CommandLine(new MyApp()).getUsageMessage();
    String expected = String.format("" +
            "Usage: myapp [-hV] [--] <file>%n" +
            "Example command.%n" +
            "      <file>      A file.%n" +
            "  -h, --help      Show this help message and exit.%n" +
            "  -V, --version   Print version information and exit.%n" +
            "  --              End of options -- rock!%n" +
            "");
    assertEquals(expected, actual);
}
 
Example #4
Source File: Generator.java    From BlockMap with MIT License 6 votes vote down vote up
@Command
public void generateTestWorld() throws IOException, InterruptedException {
	log.info("Generating test world");

	Path worldPath = OUTPUT_INTERNAL_CACHE.resolve("BlockMapWorld");

	FileUtils.copyDirectory(new File(URI.create(Generator.class.getResource("/BlockMapWorld").toString())), worldPath
			.toFile());

	Server server = new Server(OUTPUT_INTERNAL_CACHE.resolve("server-" + MinecraftVersion.LATEST.fileSuffix + ".jar"), null);
	World world = server.initWorld(worldPath, true);

	int SIZE = 256;// 256;
	ArrayList<Vector2i> chunks = new ArrayList<>(SIZE * SIZE * 4);
	for (int z = -SIZE; z < SIZE; z++)
		for (int x = -SIZE; x < SIZE; x++)
			chunks.add(new Vector2i(x, z));
	MinecraftLandGenerator.forceloadChunks(server, world, chunks, Dimension.OVERWORLD, true, 1024, true);
	world.resetChanges();

	processResources();
}
 
Example #5
Source File: SubcommandTests.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testErr_AfterSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    PrintWriter original = commandLine.getErr();
    assertNotNull(original);
    PrintWriter err = new PrintWriter(new StringWriter());
    commandLine.setErr(err);
    assertEquals(err, commandLine.getErr());

    int childCount = 0;
    int grandChildCount = 0;
    commandLine.addSubcommand("main", createNestedCommand());
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertNotSame("subcommand added afterwards is not impacted", err, sub.getErr().getClass());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertNotSame("subcommand added afterwards is not impacted", err, subsub.getErr().getClass());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #6
Source File: SubcommandTests.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testParserSplitQuotedStrings_BeforeSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    assertEquals(false, commandLine.isSplitQuotedStrings());
    commandLine.setSplitQuotedStrings(true);
    assertEquals(true, commandLine.isSplitQuotedStrings());

    int childCount = 0;
    int grandChildCount = 0;
    commandLine.addSubcommand("main", createNestedCommand());
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added afterwards is not impacted", false, sub.isSplitQuotedStrings());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subcommand added afterwards is not impacted", false, subsub.isSplitQuotedStrings());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #7
Source File: NegatableOptionTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testPlusMinusWidth() {
    @Command(name = "negatable-options-demo", mixinStandardHelpOptions = true)
    class Demo {
        @Option(names = "--verbose", negatable = true, description = "Show verbose output")
        boolean verbose;

        @Option(names = "-XX:+PrintGCDetails", negatable = true, description = "Prints GC details")
        boolean printGCDetails;

        @Option(names = "-XX:-UseG1GC", negatable = true, description = "Use G1 algorithm for GC")
        boolean useG1GC = true;
    }
    String expected = String.format("" +
            "Usage: negatable-options-demo [-hV] [--[no-]verbose] [-XX:(+|-)PrintGCDetails]%n" +
            "                              [-XX:(+|-)UseG1GC]%n" +
            "  -h, --help             Show this help message and exit.%n" +
            "  -V, --version          Print version information and exit.%n" +
            "      --[no-]verbose     Show verbose output%n" +
            "      -XX:(+|-)PrintGCDetails%n" +
            "                         Prints GC details%n" +
            "      -XX:(+|-)UseG1GC   Use G1 algorithm for GC%n");
    String actual = new CommandLine(new Demo()).getUsageMessage();
    assertEquals(expected, actual);
}
 
Example #8
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecutionStrategy_AfterSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    IExecutionStrategy original = commandLine.getExecutionStrategy();
    assertTrue(original instanceof CommandLine.RunLast);
    IExecutionStrategy strategy = new IExecutionStrategy() {
        public int execute(ParseResult parseResult) throws ExecutionException, ParameterException {
            return 0;
        }
    };
    commandLine.setExecutionStrategy(strategy);
    assertEquals(strategy, commandLine.getExecutionStrategy());

    int childCount = 0;
    int grandChildCount = 0;
    commandLine.addSubcommand("main", createNestedCommand());
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertTrue("subcommand added afterwards is not impacted", sub.getExecutionStrategy() instanceof CommandLine.RunLast);
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertTrue("subcommand added afterwards is not impacted", subsub.getExecutionStrategy() instanceof CommandLine.RunLast);
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #9
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testColorScheme_BeforeSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    commandLine.addSubcommand("main", createNestedCommand());
    CommandLine.Help.ColorScheme original = commandLine.getColorScheme();
    assertEquals(Arrays.asList(CommandLine.Help.Ansi.Style.bold), original.commandStyles());

    CommandLine.Help.ColorScheme scheme = new CommandLine.Help.ColorScheme.Builder()
            .commands(CommandLine.Help.Ansi.Style.fg_black, CommandLine.Help.Ansi.Style.bg_cyan)
            .build();
    commandLine.setColorScheme(scheme);
    assertEquals(scheme, commandLine.getColorScheme());

    int childCount = 0;
    int grandChildCount = 0;
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertSame("subcommand added before IS impacted", scheme, sub.getColorScheme());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertSame("subsubcommand added before IS impacted", scheme, sub.getColorScheme());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #10
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testParserPosixClustedShortOptions_AfterSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    commandLine.addSubcommand("main", createNestedCommand());
    assertEquals(true, commandLine.isPosixClusteredShortOptionsAllowed());
    commandLine.setPosixClusteredShortOptionsAllowed(false);
    assertEquals(false, commandLine.isPosixClusteredShortOptionsAllowed());

    int childCount = 0;
    int grandChildCount = 0;
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added before IS impacted", false, sub.isPosixClusteredShortOptionsAllowed());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subsubcommand added before IS impacted", false, sub.isPosixClusteredShortOptionsAllowed());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #11
Source File: InterpolatedModelTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterpolateFallbackValue() {
    @Command(mixinStandardHelpOptions = false)
    class AppWithFallback {
        @Option(names="--mypath", fallbackValue = "${sys:user.home}",
                description = "Path. Fallback=${FALLBACK-VALUE}.")
        private String path;
    }
    String expected = String.format("" +
                    "Usage: <main class> [--mypath=<path>]%n" +
                    "      --mypath=<path>   Path. Fallback=%1$s.%n",
            System.getProperty("user.home"));

    String actual = new CommandLine(new AppWithFallback()).getUsageMessage(CommandLine.Help.Ansi.OFF);
    assertEquals(expected, actual);
}
 
Example #12
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Command(mixinStandardHelpOptions = true)
void posAndMixin(int[] posInt, @ArgGroup(multiplicity = "0..1") Composite composite, @Mixin SomeMixin mixin) {
    this.myMixin = mixin;
    this.myComposite = composite;
    this.myPositionalInt = posInt;
    invoked.add(InvokedSub.posAndMixin);
}
 
Example #13
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testParserTrimQuotes_BeforeSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    assertEquals(false, commandLine.isTrimQuotes());
    commandLine.setTrimQuotes(true);
    assertEquals(true, commandLine.isTrimQuotes());

    int childCount = 0;
    int grandChildCount = 0;
    commandLine.addSubcommand("main", createNestedCommand());
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added afterwards is not impacted", false, sub.isTrimQuotes());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subcommand added afterwards is not impacted", false, subsub.isTrimQuotes());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #14
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testParserTrimQuotes_AfterSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    commandLine.addSubcommand("main", createNestedCommand());
    assertEquals(false, commandLine.isTrimQuotes());
    commandLine.setTrimQuotes(true);
    assertEquals(true, commandLine.isTrimQuotes());

    int childCount = 0;
    int grandChildCount = 0;
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added before IS impacted", true, sub.isTrimQuotes());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subsubcommand added before IS impacted", true, sub.isTrimQuotes());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #15
Source File: EndOfOptionsDelimiterTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndOfOptionsAndAtFileUsageWithoutParamsOrOptions() {
    @Command(name = "A",
            showAtFileInUsageHelp = true,
            showEndOfOptionsDelimiterInUsageHelp = true,
            parameterListHeading = "Parameters:%n",
            optionListHeading = "Options:%n",
            description = "... description ...")
    class A { }

    String actual = new CommandLine(new A()).getUsageMessage();
    String expected = String.format("" +
            "Usage: A [--] [@<filename>...]%n" +
            "... description ...%n" +
            "Parameters:%n" +
            "      [@<filename>...]   One or more argument files containing options.%n" +
            "Options:%n" +
            "  --                     This option can be used to separate command-line%n" +
            "                           options from the list of positional parameters.%n" +
            "");
    assertEquals(expected, actual);
}
 
Example #16
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetEndOfOptionsDelimiter_AfterSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    commandLine.addSubcommand("main", createNestedCommand());
    assertEquals("--", commandLine.getEndOfOptionsDelimiter());
    commandLine.setEndOfOptionsDelimiter("@@");
    assertEquals("@@", commandLine.getEndOfOptionsDelimiter());

    int childCount = 0;
    int grandChildCount = 0;
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added before IS impacted", "@@", sub.getEndOfOptionsDelimiter());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subsubcommand added before IS impacted", "@@", sub.getEndOfOptionsDelimiter());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #17
Source File: SplitSynopsisLabelTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionWithoutSplit() {
    @Command(name = "WithoutSplit")
    class WithoutSplit {
        @Option(names = "v", splitSynopsisLabel = "|", description = "xxx yyy zzz")
        String args[] = {};
    }

    String expected = String.format("" +
            "Usage: WithoutSplit [v=<args>]...%n" +
            "      v=<args>   xxx yyy zzz%n");
    String actual = new CommandLine(new WithoutSplit()).getUsageMessage(OFF);
    assertEquals(expected, actual);
}
 
Example #18
Source File: UnmatchedArgumentExceptionTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testHiddenCommandsNotSuggested() {

    @Command(name="Completion", subcommands = { picocli.AutoComplete.GenerateCompletion.class } )
    class CompletionSubcommandDemo implements Runnable {
        public void run() { }
    }
    Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
        public CommandLine get() {
            CommandLine cmd = new CommandLine(new CompletionSubcommandDemo());
            CommandLine gen = cmd.getSubcommands().get("generate-completion");
            gen.getCommandSpec().usageMessage().hidden(true);
            return cmd;
        }
    };

    Execution execution = Execution.builder(supplier).execute("ge");
    execution.assertSystemErr("" +
            "Unmatched argument at index 0: 'ge'%n" +
            "Usage: Completion [COMMAND]%n");
}
 
Example #19
Source File: VersionProviderTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testCommandLine_printVersionInfo_printsArrayOfPlainTextStrings() {
    @Command(version = {"Versioned Command 1.0", "512-bit superdeluxe", "(c) 2017"}) class Versioned {}
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new CommandLine(new Versioned()).printVersionHelp(new PrintStream(baos, true), CommandLine.Help.Ansi.OFF);
    String result = baos.toString();
    assertEquals(String.format("Versioned Command 1.0%n512-bit superdeluxe%n(c) 2017%n"), result);
}
 
Example #20
Source File: ModelUsageMessageSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testUsageMessageSpec_showAtFileInUsageHelp() {
    @Command(name = "blah") class MyApp {}

    CommandLine cmd = new CommandLine(new MyApp());
    String expected = String.format("" +
            "Usage: blah%n");
    assertEquals(expected, cmd.getUsageMessage());

    UsageMessageSpec spec = cmd.getCommandSpec().usageMessage();
    assertFalse(spec.showAtFileInUsageHelp());

    spec.showAtFileInUsageHelp(true);
    assertTrue(spec.showAtFileInUsageHelp());
    String expectedAfter = String.format("" +
            "Usage: blah [@<filename>...]%n" +
            "      [@<filename>...]   One or more argument files containing options.%n");
    assertEquals(expectedAfter, cmd.getUsageMessage());
}
 
Example #21
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
/** see <a href="https://github.com/remkop/picocli/issues/280">issue #280</a>  */
@SuppressWarnings("deprecation")
@Test
public void testSingleValueFieldWithOptionalParameter_280() {
    @Command(name="sample")
    class Sample {
        @Option(names="--foo", arity="0..1", fallbackValue = "123") Integer foo;
    }
    List<CommandLine> parsed1 = new CommandLine(new Sample()).parse();// not specified
    OptionSpec option1 = parsed1.get(0).getCommandSpec().optionsMap().get("--foo");
    assertNull("optional option is null when option not specified", option1.getValue());
    assertTrue("optional option has no string value when option not specified", option1.stringValues().isEmpty());
    assertTrue("optional option has no typed value when option not specified", option1.typedValues().isEmpty());

    List<CommandLine> parsed2 = new CommandLine(new Sample()).parse("--foo");// specified without value
    OptionSpec option2 = parsed2.get(0).getCommandSpec().optionsMap().get("--foo");
    assertEquals("optional option is fallback when specified without args", 123, option2.getValue());
    assertEquals("optional option string fallback value when specified without args", "123", option2.stringValues().get(0));
    assertEquals("optional option typed value when specified without args", 123, option2.typedValues().get(0));

    List<CommandLine> parsed3 = new CommandLine(new Sample()).parse("--foo", "999");// specified with value
    OptionSpec option3 = parsed3.get(0).getCommandSpec().optionsMap().get("--foo");
    assertEquals("optional option is empty string when specified with args", 999, option3.getValue());
    assertEquals("optional option string value when specified with args", "999", option3.stringValues().get(0));
    assertEquals("optional option typed value when specified with args", 999, option3.typedValues().get(0));
}
 
Example #22
Source File: VersionProviderTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testCommandLine_printVersionInfo_printsSingleStringWithMarkup() {
    @Command(version = "@|red 1.0|@") class Versioned {}
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new CommandLine(new Versioned()).printVersionHelp(new PrintStream(baos, true), CommandLine.Help.Ansi.ON);
    String result = baos.toString();
    assertEquals(String.format("\u001B[31m1.0\u001B[39m\u001B[0m%n"), result);
}
 
Example #23
Source File: Sub.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Command
void subsubmethod(@Mixin LoggingMixin loggingMixin) {
    logger.trace("Hi (tracing)   from app sub subsubmethod");
    logger.debug("Hi (debugging) from app sub subsubmethod");
    logger.info ("Hi (info)      from app sub subsubmethod");
    logger.warn ("Hi (warning)   from app sub subsubmethod");
}
 
Example #24
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testParserUnmatchedOptionsArePositionalParams_AfterSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    commandLine.addSubcommand("main", createNestedCommand());
    assertEquals(false, commandLine.isUnmatchedOptionsArePositionalParams());
    commandLine.setUnmatchedOptionsArePositionalParams(true);
    assertEquals(true, commandLine.isUnmatchedOptionsArePositionalParams());

    int childCount = 0;
    int grandChildCount = 0;
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added before IS impacted", true, sub.isUnmatchedOptionsArePositionalParams());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subsubcommand added before IS impacted", true, sub.isUnmatchedOptionsArePositionalParams());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #25
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testParserPosixClustedShortOptions_BeforeSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    assertEquals(true, commandLine.isPosixClusteredShortOptionsAllowed());
    commandLine.setPosixClusteredShortOptionsAllowed(false);
    assertEquals(false, commandLine.isPosixClusteredShortOptionsAllowed());

    int childCount = 0;
    int grandChildCount = 0;
    commandLine.addSubcommand("main", createNestedCommand());
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added afterwards is not impacted", true, sub.isPosixClusteredShortOptionsAllowed());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subcommand added afterwards is not impacted", true, subsub.isPosixClusteredShortOptionsAllowed());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #26
Source File: SubcommandTests.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetSeparator_BeforeSubcommandsAdded() {
    @Command
    class TopLevel {}
    CommandLine commandLine = new CommandLine(new TopLevel());
    assertEquals("=", commandLine.getSeparator());
    commandLine.setSeparator(":");
    assertEquals(":", commandLine.getSeparator());

    int childCount = 0;
    int grandChildCount = 0;
    commandLine.addSubcommand("main", createNestedCommand());
    for (CommandLine sub : commandLine.getSubcommands().values()) {
        childCount++;
        assertEquals("subcommand added afterwards is not impacted", "=", sub.getSeparator());
        for (CommandLine subsub : sub.getSubcommands().values()) {
            grandChildCount++;
            assertEquals("subcommand added afterwards is not impacted", "=", subsub.getSeparator());
        }
    }
    assertTrue(childCount > 0);
    assertTrue(grandChildCount > 0);
}
 
Example #27
Source File: ManPageGeneratorTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndOfOptions() throws IOException {

    @Command(name = "testEndOfOptions", mixinStandardHelpOptions = true,
            showEndOfOptionsDelimiterInUsageHelp = true,
            version = { "Versioned Command 1.0"},
            description = "This app does great things."
    )
    class MyApp {
        @Option(names = {"-o", "--output"}, description = "Output location full path.")
        File outputFolder;

        @Parameters(description = "Some values")
        List<String> values;
    }

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw); //System.out, true
    ManPageGenerator.writeSingleManPage(pw, new CommandLine(new MyApp()).getCommandSpec());
    pw.flush();

    String expected = read("/testEndOfOptions.manpage.adoc");
    expected = expected.replace("\r\n", "\n");
    expected = expected.replace("\n", System.getProperty("line.separator"));
    assertEquals(expected, sw.toString());
}
 
Example #28
Source File: ManPageGeneratorTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testHiddenOptions() throws IOException {

    @Command(name = "testHiddenOptions",
            version = {
                    "Versioned Command 1.0",
                    "Picocli " + picocli.CommandLine.VERSION,
                    "JVM: ${java.version} (${java.vendor} ${java.vm.name} ${java.vm.version})",
                    "OS: ${os.name} ${os.version} ${os.arch}"},
            description = "This app does great things."
    )
    class MyApp {
        @Option(names = {"-o", "--output"}, hidden = true, description = "Output location full path.")
        File outputFolder;

        @Option(names = {"--hidden-test"}, hidden = true)
        File hidden;

        @Parameters(hidden = true)
        List<String> values;
    }

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw); //System.out, true
    ManPageGenerator.writeSingleManPage(pw, new CommandLine(new MyApp()).getCommandSpec());
    pw.flush();

    String expected = read("/testHiddenOptions.manpage.adoc");
    expected = expected.replace("\r\n", "\n");
    expected = expected.replace("\n", System.getProperty("line.separator"));
    assertEquals(expected, sw.toString());
}
 
Example #29
Source File: EndOfOptionsDelimiterTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndOfOptionsDelimiter() {
    @Command(name = "A", mixinStandardHelpOptions = true,
            showEndOfOptionsDelimiterInUsageHelp = true,
            description = "... description ...")
    class A {
        @Parameters(arity = "1", description = "The file.")
        private File file;

        @Option(names = {"-x", "--long"}, arity="0..*", description = "Option with multiple params.")
        private String params;
    }

    String actual = new CommandLine(new A()).getUsageMessage();
    String expected = String.format("" +
            "Usage: A [-hV] [-x[=<params>...]] [--] <file>%n" +
            "... description ...%n" +
            "      <file>                 The file.%n" +
            "  -h, --help                 Show this help message and exit.%n" +
            "  -V, --version              Print version information and exit.%n" +
            "  -x, --long[=<params>...]   Option with multiple params.%n" +
            "  --                         This option can be used to separate command-line%n" +
            "                               options from the list of positional parameters.%n" +
            "");
    assertEquals(expected, actual);
}
 
Example #30
Source File: EndOfOptionsDelimiterTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testShowEndOfOptionsDelimiterInUsageHelpWithCustomEndOfOptionsDelimiter() {
    @Command(name = "A", mixinStandardHelpOptions = true,
            showEndOfOptionsDelimiterInUsageHelp = true, description = "... description ...")
    class A { }

    String actual = new CommandLine(new A())
            .setEndOfOptionsDelimiter("@+@")
            .getUsageMessage();

    String expected = String.format("" +
            "Usage: A [-hV] [@+@]%n" +
            "... description ...%n" +
            "  -h, --help      Show this help message and exit.%n" +
            "  -V, --version   Print version information and exit.%n" +
            "      @+@         This option can be used to separate command-line options from%n" +
            "                    the list of positional parameters.%n" +
            "");
    assertEquals(expected, actual);
}