picocli.CommandLine.Parameters Java Examples

The following examples show how to use picocli.CommandLine.Parameters. 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: InteractiveArgTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testInteractivePositionalAsCharArray() throws IOException {
    class App {
        @Parameters(index = "0", description = {"Pwd", "line2"}, interactive = true)
        char[] x;
        @Parameters(index = "1") int z;
    }

    PrintStream out = System.out;
    InputStream in = System.in;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.setOut(new PrintStream(baos));
        System.setIn(inputStream("123"));
        App app = new App();
        CommandLine cmd = new CommandLine(app);
        cmd.parseArgs("9");

        assertEquals("Enter value for position 0 (Pwd): ", baos.toString());
        assertArrayEquals("123".toCharArray(), app.x);
        assertEquals(9, app.z);
    } finally {
        System.setOut(out);
        System.setIn(in);
    }
}
 
Example #2
Source File: AtFileTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testShowAtFileInUsageHelpBasic() {
    @Command(name = "myapp", mixinStandardHelpOptions = true,
            showAtFileInUsageHelp = true, description = "Example command.")
    class MyApp {
        @Parameters(description = "A file.") File file;
    }

    String actual = new CommandLine(new MyApp()).getUsageMessage();
    String expected = String.format("" +
            "Usage: myapp [-hV] [@<filename>...] <file>%n" +
            "Example command.%n" +
            "      [@<filename>...]   One or more argument files containing options.%n" +
            "      <file>             A file.%n" +
            "  -h, --help             Show this help message and exit.%n" +
            "  -V, --version          Print version information and exit.%n");
    assertEquals(expected, actual);
}
 
Example #3
Source File: RangeTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultRange() {
    class R1 {
        @Parameters int a;
    }
    PositionalParamSpec positional = new CommandLine(new R1()).getCommandSpec().positionalParameters().get(0);
    CommandLine.Range range = positional.index();
    assertEquals(0, range.min());
    assertEquals(0, range.max());
    assertEquals(false, range.isUnspecified());
    assertEquals(true, range.isRelative());
    assertEquals(false, range.isVariable());
    assertEquals(false, range.isUnresolved());
    assertEquals("0", range.toString());
    assertEquals("0+ (0)", range.internalToString());
}
 
Example #4
Source File: AbstractCommandSpecProcessor.java    From picocli with Apache License 2.0 6 votes vote down vote up
private boolean isSubcommand(ExecutableElement method, RoundEnvironment roundEnv) {
    Element typeElement = method.getEnclosingElement();
    if (typeElement.getAnnotation(Command.class) != null && typeElement.getAnnotation(Command.class).addMethodSubcommands()) {
        return true;
    }
    if (typeElement.getAnnotation(Command.class) == null) {
        Set<Element> elements = new HashSet<Element>(typeElement.getEnclosedElements());

        // The class is a Command if it has any fields or methods annotated with the below:
        return roundEnv.getElementsAnnotatedWith(Option.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Parameters.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Mixin.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(ArgGroup.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Unmatched.class).removeAll(elements)
                || roundEnv.getElementsAnnotatedWith(Spec.class).removeAll(elements);
    }
    return false;
}
 
Example #5
Source File: InteractiveArgTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testInteractivePositionalArity_0_1_ConsumesFromCommandLineIfPossible() throws IOException {
    class App {
        @Parameters(index = "0", arity = "0..1", interactive = true)
        char[] x;

        @Parameters(index = "1")
        String[] remainder;
    }

    PrintStream out = System.out;
    InputStream in = System.in;
    try {
        System.setOut(new PrintStream(new ByteArrayOutputStream()));
        System.setIn(inputStream("123"));
        App app = new App();
        CommandLine cmd = new CommandLine(app);
        cmd.parseArgs("456", "abc");

        assertArrayEquals("456".toCharArray(), app.x);
        assertArrayEquals(new String[]{"abc"}, app.remainder);
    } finally {
        System.setOut(out);
        System.setIn(in);
    }
}
 
Example #6
Source File: AtFileTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testAtFileExpandedWithCommentsOff() {
    class App {
        @Option(names = "-x")
        private boolean xxx;

        @Option(names = "-f")
        private String[] fff;

        @Option(names = "-v")
        private boolean verbose;

        @Parameters
        private List<String> files;
    }
    File file = findFile("/argfile1.txt");
    App app = new App();
    CommandLine cmd = new CommandLine(app);
    cmd.setAtFileCommentChar(null);
    cmd.parseArgs("-f", "fVal1", "@" + file.getAbsolutePath(), "-x", "-f", "fVal2");
    assertTrue(app.verbose);
    assertEquals(Arrays.asList("#", "first", "comment", "1111", "2222", "#another", "comment", ";3333"), app.files);
    assertTrue(app.xxx);
    assertArrayEquals(new String[]{"fVal1", "fVal2"}, app.fff);
}
 
Example #7
Source File: UnmatchedOptionTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiValueVarArgPositionalDoesNotConsumeActualOption() {
    class App {
        @Option(names = "-x") int x;
        @Parameters(arity = "*") String[] y;
    }

    expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "-x");
    expect(new App(), "option '-x' (<x>) should be specified only once", OverwrittenOptionException.class, "-x", "3", "-x", "4");

    expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "4", "-x");

    App app = new App();
    new CommandLine(app).parseArgs("-x", "3", "4");
    assertEquals(3, app.x);
    assertArrayEquals(new String[]{"4"}, app.y);
}
 
Example #8
Source File: UnmatchedOptionTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiValuePositionalArity2_NDoesNotConsumeActualOption() {
    class App {
        @Option(names = "-x") int x;
        @Parameters(arity = "2..*") String[] y;
    }

    expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "-x");
    expect(new App(), "option '-x' (<x>) should be specified only once", OverwrittenOptionException.class, "-x", "3", "-x", "4");

    expect(new App(), "Expected parameter 2 (of 2 mandatory parameters) for positional parameter at index 0..* (<y>) but found '-x'",
            MissingParameterException.class, "-x", "3", "4", "-x");

    App app = new App();
    new CommandLine(app).parseArgs("-x", "3", "4", "5");
    assertEquals(3, app.x);
    assertArrayEquals(new String[]{"4", "5"}, app.y);
}
 
Example #9
Source File: AtFileTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testAtFileNotExpandedIfDisabled() {
    class App {
        @Option(names = "-v")
        private boolean verbose;

        @Parameters
        private List<String> files;
    }
    File file = findFile("/argfile1.txt");
    assertTrue(file.getAbsoluteFile().exists());
    App app = new App();
    new CommandLine(app).setExpandAtFiles(false).parseArgs("@" + file.getAbsolutePath());
    assertFalse(app.verbose);
    assertEquals(Arrays.asList("@" + file.getAbsolutePath()), app.files);
}
 
Example #10
Source File: UnmatchedOptionTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiValuePositionalCanBeConfiguredToConsumeUnknownOption() {
    class App {
        @Option(names = "-x") int x;
        @Parameters String[] y;
    }

    App app = new App();
    new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "-z");
    assertEquals(3, app.x);
    assertArrayEquals(new String[]{"-z"}, app.y);

    app = new App();
    new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "-z", "4");
    assertEquals(3, app.x);
    assertArrayEquals(new String[]{"-z", "4"}, app.y);

    app = new App();
    new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "4", "-z");
    assertEquals(3, app.x);
    assertArrayEquals(new String[]{"4", "-z"}, app.y);
}
 
Example #11
Source File: AtFileTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testAtFileWithQuotedValuesContainingWhitespace() {
    class App {
        @Option(names = "-x")
        private boolean xxx;

        @Option(names = "-f")
        private String[] fff;

        @Option(names = "-v")
        private boolean verbose;

        @Parameters
        private List<String> files;
    }
    setTraceLevel("OFF");
    File file = findFile("/argfile4-quotedValuesContainingWhitespace.txt");
    App app = CommandLine.populateCommand(new App(), "-f", "fVal1", "@" + file.getAbsolutePath(), "-f", "fVal2");
    assertTrue(app.verbose);
    assertEquals(Arrays.asList("11 11", "22\n22", "3333"), app.files);
    assertTrue(app.xxx);
    assertArrayEquals(new String[]{"fVal1", "F F F F", "F2 F2 F2", "fVal2"}, app.fff);
}
 
Example #12
Source File: ModelPositionalParamSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testParameterHasCommand() {
    class App {
        @Parameters(index="0") int x;
    }

    CommandSpec cmd = new CommandLine(new App()).getCommandSpec();
    CommandSpec cmd2 = new CommandLine(new App()).getCommandSpec();
    PositionalParamSpec param = cmd.positionalParameters().get(0);
    assertEquals(cmd, param.command());
    PositionalParamSpec param1 = PositionalParamSpec.builder().index("1").build();
    assertEquals(null, param1.command());
    cmd.add(param1);
    assertEquals(cmd, param1.command());
    cmd2.add(param1);
    assertEquals(cmd2, param1.command());
    assertEquals(param1, cmd.positionalParameters().get(1));
}
 
Example #13
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testPositionalParamSpec_defaultValue_overwritesInitialValue() {
    class Params {
        @Parameters int num = 12345;
    }
    CommandLine cmd = new CommandLine(new Params());
    PositionalParamSpec x = cmd.getCommandSpec().positionalParameters().get(0).toBuilder().defaultValue("54321").build();

    cmd = new CommandLine(CommandSpec.create().add(x));
    ParseResult parseResult = cmd.parseArgs();

    // default not in the parse result
    assertFalse(parseResult.hasMatchedPositional(0));
    assertEquals(Integer.valueOf(-1), parseResult.matchedPositionalValue(0, -1));

    // but positional spec does have the default value
    assertEquals(Integer.valueOf(54321), parseResult.commandSpec().positionalParameters().get(0).getValue());

}
 
Example #14
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testInject_AnnotatedFieldInjectedForSubcommand() {
    class Injected {
        @Spec CommandSpec commandSpec;
        @Parameters String[] params;
    }
    Injected injected = new Injected();
    Injected sub = new Injected();

    assertNull(injected.commandSpec);
    assertNull(sub.commandSpec);

    CommandLine cmd = new CommandLine(injected);
    assertSame(cmd.getCommandSpec(), injected.commandSpec);

    CommandLine subcommand = new CommandLine(sub);
    assertSame(subcommand.getCommandSpec(), sub.commandSpec);
}
 
Example #15
Source File: RangeTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserManualAutomaticIndexExample() {
    class AutomaticIndex {
        @Parameters(hidden = true)  // "hidden": don't show this parameter in usage help message
        List<String> allParameters; // no "index" attribute: captures _all_ arguments (as Strings)

        @Parameters String group;    // assigned index = "0"
        @Parameters String artifact; // assigned index = "1"
        @Parameters String version;  // assigned index = "2"
    }
    //TestUtil.setTraceLevel("DEBUG");
    String[] args = { "info.picocli", "picocli", "4.3.0" };
    AutomaticIndex params = CommandLine.populateCommand(new AutomaticIndex(), args);

    assertEquals("info.picocli", params.group);
    assertEquals("picocli", params.artifact);
    assertEquals("4.3.0", params.version);
    assertEquals(Arrays.asList("info.picocli", "picocli", "4.3.0"), params.allParameters);
}
 
Example #16
Source File: RangeTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
// test for https://github.com/remkop/picocli/issues/564
public void testMixinsWithVariableIndex() {
    @Command(name = "testCommand", description = "Example for issue 564")
    class TestCommand {

        @Mixin private CommonMixinOne myCommonMixinOne;

        @Parameters(index = "1", paramLabel = "TEST-COMMAND-PARAM")
        private String testCommandParam;

        @Mixin private CommonMixinTwo myCommonMixinTwo;
    }

    CommandLine cmd = new CommandLine(new TestCommand());

    String expected = String.format("" +
            "Usage: testCommand COMMON-PARAM-ONE TEST-COMMAND-PARAM COMMON-PARAM-TWO%n" +
            "Example for issue 564%n" +
            "      COMMON-PARAM-ONE%n" +
            "      TEST-COMMAND-PARAM%n" +
            "      COMMON-PARAM-TWO%n");
    String actual = cmd.getUsageMessage();
    assertEquals(expected, actual);
}
 
Example #17
Source File: ParentCommandTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitializationExceptionForTypeMismatch() {
    class Top1 {
        @Option(names = {"-d", "--directory"}, description = "this option applies to all subcommands")
        private File baseDirectory;
    }
    class Sub1 {
        @ParentCommand private String parent;
        @Parameters private int count;
    }
    Top1 top1 = new Top1();
    Sub1 sub1 = new Sub1();
    try {
        new CommandLine(top1).addSubcommand("sub1", sub1);
        fail("expected failure");
    } catch (InitializationException ex) {
        String prefix = "Unable to initialize @ParentCommand field: picocli.CommandLine$PicocliException";
        if (prefix.equals(ex.getMessage())) { return; }
        String expected = prefix + ": Could not set value for field private java.lang.String " + sub1.getClass().getName() + ".parent to " + top1;
        assertEquals(expected, ex.getMessage());
    }
}
 
Example #18
Source File: ParameterConsumerTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndexOfPositionalParameterConsumer() {
    class App {
        @Parameters(index = "0", parameterConsumer = FindExecParameterConsumer.class)
        List<String> list = new ArrayList<String>();

        @Parameters(index = "1..*", parameterConsumer = FindExecParameterConsumer.class)
        List<String> remainder = new ArrayList<String>();

        @Option(names = "-y") boolean y;
    }

    App app = CommandLine.populateCommand(new App(), "00 a b ; c d".split(" "));
    assertEquals(Arrays.asList("00", "a", "b", ";"), app.list);
    assertEquals(Arrays.asList("c", "d"), app.remainder);
    assertFalse(app.y);

    App other = CommandLine.populateCommand(new App(), "0 a b ; -y c d".split(" "));
    assertEquals(Arrays.asList("0", "a", "b", ";"), other.list);
    assertEquals(Arrays.asList("c", "d"), other.remainder);
    assertTrue(other.y);
}
 
Example #19
Source File: ArgSplitTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testSplitInParametersCollection() {
    class Args {
        @Parameters(split = ",") List<String> values;
    }
    Args args = CommandLine.populateCommand(new Args(), "a,b,c");
    assertEquals(Arrays.asList("a", "b", "c"), args.values);

    args = CommandLine.populateCommand(new Args(), "a,b,c", "B", "C");
    assertEquals(Arrays.asList("a", "b", "c", "B", "C"), args.values);

    args = CommandLine.populateCommand(new Args(), "a,b,c", "B", "C");
    assertEquals(Arrays.asList("a", "b", "c", "B", "C"), args.values);

    args = CommandLine.populateCommand(new Args(), "a,b,c", "B", "C", "D,E,F");
    assertEquals(Arrays.asList("a", "b", "c", "B", "C", "D", "E", "F"), args.values);
}
 
Example #20
Source File: ArgSplitTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testSplitInParametersArray() {
    class Args {
        @Parameters(split = ",") String[] values;
    }
    Args args = CommandLine.populateCommand(new Args(), "a,b,c");
    assertArrayEquals(new String[] {"a", "b", "c"}, args.values);

    args = CommandLine.populateCommand(new Args(), "a,b,c", "B", "C");
    assertArrayEquals(new String[] {"a", "b", "c", "B", "C"}, args.values);

    args = CommandLine.populateCommand(new Args(), "a,b,c", "B", "C");
    assertArrayEquals(new String[] {"a", "b", "c", "B", "C"}, args.values);

    args = CommandLine.populateCommand(new Args(), "a,b,c", "B", "C", "D,E,F");
    assertArrayEquals(new String[] {"a", "b", "c", "B", "C", "D", "E", "F"}, args.values);
}
 
Example #21
Source File: RangeTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testRelativeRangeWithoutAnchor() {
    class App {
        @Parameters(index = "+", descriptionKey = "a") String a;
        @Parameters(index = "+", descriptionKey = "b") String b;
        @Parameters(index = "+", descriptionKey = "c") String c;
    }

    CommandLine cmd = new CommandLine(new App());
    List<PositionalParamSpec> positionals = cmd.getCommandSpec().positionalParameters();
    assertEquals("a", positionals.get(0).descriptionKey());
    assertEquals(0, positionals.get(0).index().min());
    assertEquals(0, positionals.get(0).index().max());

    assertEquals("b", positionals.get(1).descriptionKey());
    assertEquals(1, positionals.get(1).index().min());
    assertEquals(1, positionals.get(1).index().max());

    assertEquals("c", positionals.get(2).descriptionKey());
    assertEquals(2, positionals.get(2).index().min());
    assertEquals(2, positionals.get(2).index().max());
}
 
Example #22
Source File: AtFileTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testAtFileWithMultipleValuesPerLine() {
    class App {
        @Option(names = "-x")
        private boolean xxx;

        @Option(names = "-f")
        private String[] fff;

        @Option(names = "-v")
        private boolean verbose;

        @Parameters
        private List<String> files;
    }
    File file = findFile("/argfile3-multipleValuesPerLine.txt");
    App app = CommandLine.populateCommand(new App(), "-f", "fVal1", "@" + file.getAbsolutePath(), "-f", "fVal2");
    assertTrue(app.verbose);
    assertEquals(Arrays.asList("1111", "2222", "3333"), app.files);
    assertTrue(app.xxx);
    assertArrayEquals(new String[]{"fVal1", "FFFF", "F2F2F2", "fVal2"}, app.fff);
}
 
Example #23
Source File: TypeConversionTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testAnnotateCustomConverter() {
    class App {
        @Parameters(converter = MyGlobConverter.class)
        MyGlob globField;
    }
    CommandLine commandLine = new CommandLine(new App());

    String[] args = {"a*glob*pattern"};
    List<CommandLine> parsed = commandLine.parse(args);
    assertEquals("not empty", 1, parsed.size());
    assertTrue(parsed.get(0).getCommand() instanceof App);
    App app = (App) parsed.get(0).getCommand();
    assertEquals(args[0], app.globField.glob);
}
 
Example #24
Source File: AtFileTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testShowAtFileInUsageHelpSystemProperties() {
    @Command(name = "myapp", mixinStandardHelpOptions = true,
            showAtFileInUsageHelp = true, description = "Example command.")
    class MyApp {
        @Parameters(description = "A file.") File file;
    }

    System.setProperty("picocli.atfile.label", "my@@@@file");
    System.setProperty("picocli.atfile.description", "@files rock!");

    String actual = new CommandLine(new MyApp()).getUsageMessage();
    String expected = String.format("" +
            "Usage: myapp [-hV] [my@@@@file...] <file>%n" +
            "Example command.%n" +
            "      [my@@@@file...]   @files rock!%n" +
            "      <file>            A file.%n" +
            "  -h, --help            Show this help message and exit.%n" +
            "  -V, --version         Print version information and exit.%n");
    assertEquals(expected, actual);
}
 
Example #25
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequiredArgsInAGroupAreNotValidated() {
    class App {
        @ArgGroup(exclusive = true, multiplicity = "0..1")
        Object exclusive = new Object() {
            @Option(names = "-x", required = true) boolean x;

            @ArgGroup(exclusive = false, multiplicity = "1")
            Object all = new Object() {
                @Option(names = "-a", required = true) int a;
                @Parameters(index = "0") File f0;
            };
        };
    }
    String expected = String.format("" +
            "Usage: <main class> [-x | (-a=<a> <f0>)]%n" +
            "      <f0>%n" +
            "  -a=<a>%n" +
            "  -x%n");

    CommandLine cmd = new CommandLine(new App());
    String actual = cmd.getUsageMessage(Help.Ansi.OFF);
    assertEquals(expected, actual);

    cmd.parseArgs(); // no error
}
 
Example #26
Source File: EndOfOptionsDelimiterTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndOfOptionsListSectionBeforeOptions() {
    @Command(name = "A", mixinStandardHelpOptions = true,
            optionListHeading = "Options:%n",
            showEndOfOptionsDelimiterInUsageHelp = true, description = "... description ...")
    class A {
        @Parameters(index = "0", arity = "1", description = "Some file.") File file;
        @Parameters(index = "1", description = "Some other file.") File anotherFile;
    }

    CommandLine commandLine = new CommandLine(new A());
    List<String> helpSectionKeys = commandLine.getHelpSectionKeys();
    List<String> copy = new ArrayList<String>(helpSectionKeys);
    copy.remove(SECTION_KEY_END_OF_OPTIONS);
    copy.add(helpSectionKeys.indexOf(SECTION_KEY_OPTION_LIST_HEADING), SECTION_KEY_END_OF_OPTIONS);
    commandLine.setHelpSectionKeys(copy);

    String actual = commandLine.getUsageMessage();
    String expected = String.format("" +
            "Usage: A [-hV] [--] <file> <anotherFile>%n" +
            "... description ...%n" +
            "      <file>          Some file.%n" +
            "      <anotherFile>   Some other file.%n" +
            "  --                  This option can be used to separate command-line options%n" +
            "                        from the list of positional parameters.%n" +
            "Options:%n" +
            "  -h, --help          Show this help message and exit.%n" +
            "  -V, --version       Print version information and exit.%n" +
            "");
    assertEquals(expected, actual);
}
 
Example #27
Source File: TypeConversionTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testMapArgumentsMustContainEquals() {
    class App {
        @Parameters Map<String, String> map;
    }
    try {
        CommandLine.populateCommand(new App(), "a:c", "1:3");
    } catch (UnmatchedArgumentException ex) {
        assertEquals("Unmatched arguments from index 0: 'a:c', '1:3'", ex.getMessage());
    }
}
 
Example #28
Source File: ArgSplitTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplitInOptionArrayWithArity() {
    class Args {
        @Option(names = "-a", split = ",", arity = "0..4") String[] values;
        @Parameters() String[] params;
    }
    Args args = CommandLine.populateCommand(new Args(), "-a=a,b,c"); // 1 args
    assertArrayEquals(new String[] {"a", "b", "c"}, args.values);

    args = CommandLine.populateCommand(new Args(), "-a"); // 0 args
    assertArrayEquals(new String[0], args.values);
    assertNull(args.params);

    args = CommandLine.populateCommand(new Args(), "-a=a,b,c", "B", "C"); // 3 args
    assertArrayEquals(new String[] {"a", "b", "c", "B", "C"}, args.values);
    assertNull(args.params);

    args = CommandLine.populateCommand(new Args(), "-a", "a,b,c", "B", "C"); // 3 args
    assertArrayEquals(new String[] {"a", "b", "c", "B", "C"}, args.values);
    assertNull(args.params);

    args = CommandLine.populateCommand(new Args(), "-a=a,b,c", "B", "C", "D,E,F"); // 4 args
    assertArrayEquals(new String[] {"a", "b", "c", "B", "C", "D", "E", "F"}, args.values);
    assertNull(args.params);

    args = CommandLine.populateCommand(new Args(), "-a=a,b,c,d", "B", "C", "D", "E,F"); // 5 args
    assertArrayEquals(new String[] {"a", "b", "c", "d", "B", "C", "D"}, args.values);
    assertArrayEquals(new String[] {"E,F"}, args.params);
}
 
Example #29
Source File: ModelPositionalParamSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testPositionalInteractiveReadFromAnnotation() {
    class App {
        @Parameters(index = "0", interactive = true) int x;
        @Parameters(index = "1", interactive = false) int y;
        @Parameters(index = "2") int z;
    }

    CommandLine cmd = new CommandLine(new App());
    assertTrue(cmd.getCommandSpec().positionalParameters().get(0).interactive());
    assertFalse(cmd.getCommandSpec().positionalParameters().get(1).interactive());
    assertFalse(cmd.getCommandSpec().positionalParameters().get(2).interactive());
}
 
Example #30
Source File: InteractiveArgTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testInteractivePositionalAsListOfCharArraysArity_0_1_DoesNotConsumeUnknownOption() throws IOException {
    class App {
        @Parameters(index = "0..1", arity = "0..1", interactive = true)
        List<char[]> x;

        @Option(names = "-z")
        int z;

        @Parameters(index = "2")
        String[] remainder;
    }

    PrintStream out = System.out;
    InputStream in = System.in;
    try {
        System.setOut(new PrintStream(new ByteArrayOutputStream()));
        System.setIn(inputStream("123"));
        App app = new App();
        CommandLine cmd = new CommandLine(app);
        try {
            cmd.parseArgs("-y", "-w", "456", "abc");
            fail("Expect exception");
        } catch (UnmatchedArgumentException ex) {
            assertEquals("Unknown options: '-y', '-w'", ex.getMessage());
        }
    } finally {
        System.setOut(out);
        System.setIn(in);
    }
}