picocli.CommandLine.ParseResult Java Examples

The following examples show how to use picocli.CommandLine.ParseResult. 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: ModelCommandSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testTypedValues() {
    class App {
        @Option(names="-x") int x;
    }
    ParseResult result1 = new CommandLine(new App()).parseArgs();// not specified
    assertFalse(result1.hasMatchedOption('x'));
    assertTrue(result1.commandSpec().findOption('x').typedValues().isEmpty());

    ParseResult result2 = new CommandLine(new App()).parseArgs("-x", "123");
    assertTrue(result2.hasMatchedOption('x'));
    assertEquals(Integer.valueOf(123), result2.matchedOptionValue('x', 0));

    ParseResult result3 = new CommandLine(new App())
            .setOverwrittenOptionsAllowed(true)
            .parseArgs("-x", "1", "-x", "2", "-x", "3");
    assertTrue(result3.hasMatchedOption('x'));
    assertEquals(Integer.valueOf(3), result3.matchedOptionValue('x', 0));
    assertEquals(Arrays.asList("1", "2", "3"), result3.matchedOption('x').stringValues());
    assertEquals(Arrays.asList(1, 2, 3), result3.matchedOption('x').typedValues());
}
 
Example #2
Source File: OrderedOptionsTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testOrderWithParseResult() {
    CommandLine cmd = new CommandLine(new Rsync());
    ParseResult parseResult = cmd.parseArgs("--include", "a", "--exclude", "b", "--include", "c", "--exclude", "d");
    List<ArgSpec> argSpecs = parseResult.matchedArgs();
    assertEquals(4, argSpecs.size());
    assertEquals("--include", ((OptionSpec) argSpecs.get(0)).longestName());
    assertEquals("--exclude", ((OptionSpec) argSpecs.get(1)).longestName());
    assertEquals("--include", ((OptionSpec) argSpecs.get(2)).longestName());
    assertEquals("--exclude", ((OptionSpec) argSpecs.get(3)).longestName());

    List<OptionSpec> matchedOptions = parseResult.matchedOptions();
    assertEquals(4, matchedOptions.size());

    assertEquals("--include", matchedOptions.get(0).longestName());
    assertSame(matchedOptions.get(0), matchedOptions.get(2));
    assertEquals(Arrays.asList("a"), matchedOptions.get(0).typedValues().get(0));
    assertEquals(Arrays.asList("c"), matchedOptions.get(2).typedValues().get(1));

    assertEquals("--exclude", matchedOptions.get(1).longestName());
    assertSame(matchedOptions.get(1), matchedOptions.get(3));
    assertEquals(Arrays.asList("b"), matchedOptions.get(1).typedValues().get(0));
    assertEquals(Arrays.asList("d"), matchedOptions.get(3).typedValues().get(1));
}
 
Example #3
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseResetsRawAndOriginalStringValues() {
    CommandSpec spec = CommandSpec.create()
            .addOption(OptionSpec.builder("-x").type(String.class).build())
            .addPositional(PositionalParamSpec.builder().build());
    CommandLine cmd = new CommandLine(spec);
    ParseResult parseResult = cmd.parseArgs("-x", "XVAL", "POSITIONAL");
    assertEquals("XVAL", parseResult.matchedOption('x').getValue());
    assertEquals(Arrays.asList("XVAL"), parseResult.matchedOption('x').stringValues());
    assertEquals(Arrays.asList("XVAL"), parseResult.matchedOption('x').originalStringValues());
    assertEquals("POSITIONAL", parseResult.matchedPositional(0).getValue());
    assertEquals(Arrays.asList("POSITIONAL"), parseResult.matchedPositional(0).stringValues());
    assertEquals(Arrays.asList("POSITIONAL"), parseResult.matchedPositional(0).originalStringValues());

    ParseResult parseResult2 = cmd.parseArgs("-x", "222", "$$$$");
    assertEquals("222", parseResult2.matchedOption('x').getValue());
    assertEquals(Arrays.asList("222"), parseResult2.matchedOption('x').stringValues());
    assertEquals(Arrays.asList("222"), parseResult2.matchedOption('x').originalStringValues());
    assertEquals("$$$$", parseResult2.matchedPositional(0).getValue());
    assertEquals(Arrays.asList("$$$$"), parseResult2.matchedPositional(0).stringValues());
    assertEquals(Arrays.asList("$$$$"), parseResult2.matchedPositional(0).originalStringValues());

}
 
Example #4
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testClusteredAndAttached() {
    class App {
        @Option(names = "-x") boolean extract;
        @Option(names = "-v") boolean verbose;
        @Option(names = "-f") File file;
        @Option(names = "-o") File outputFile;
        @Option(names = "-i") File inputFile;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult pr = cmd.parseArgs("-xvfFILE", "-oOUT", "-iOUT");

    assertSame(pr.commandSpec().findOption("-f"), pr.tentativeMatch.get(0));
    assertSame(pr.commandSpec().findOption("-o"), pr.tentativeMatch.get(1));
    assertSame(pr.commandSpec().findOption("-i"), pr.tentativeMatch.get(2));
    assertEquals(3, pr.tentativeMatch.size());
}
 
Example #5
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testRawOptionValue() {
    class App {
        @Option(names = {"-x", "++XX", "/XXX"}) String[] x;
        @Option(names = "-y") String y;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("-x", "value1", "-x", "value2");
    assertEquals("value1", parseResult.matchedOption("x").stringValues().get(0));
    assertEquals("value1", parseResult.matchedOption("-x").stringValues().get(0));
    assertEquals("value1", parseResult.matchedOption("XX").stringValues().get(0));
    assertEquals("value1", parseResult.matchedOption("++XX").stringValues().get(0));
    assertEquals("value1", parseResult.matchedOption("XXX").stringValues().get(0));
    assertEquals("value1", parseResult.matchedOption("/XXX").stringValues().get(0));

    assertEquals(null, parseResult.matchedOption("y"));
    assertEquals(null, parseResult.matchedOption("-y"));
}
 
Example #6
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testOptionWithNonJavaIdentifierName() {
    class App {
        @Option(names = "-") String dash;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("-", "val");

    assertEquals("val", parseResult.matchedOption('-').stringValues().get(0));
    assertEquals("val", parseResult.matchedOption("-").stringValues().get(0));
    assertEquals("val", parseResult.matchedOptionValue('-', "val"));
    assertEquals("val", parseResult.matchedOptionValue("-", "val"));

    assertNull("empty string should not match", parseResult.matchedOption(""));
    assertNull("empty string should not match", parseResult.matchedOptionValue("", null));
}
 
Example #7
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testHasMatchedPositionalByPositionalSpec() {
    class App {
        @Option(names = "-x") String x;
        @Parameters(index = "0", arity = "0..1") int index0 = -1;
        @Parameters(index = "1", arity = "0..1") int index1 = -1;
        @Parameters(index = "2", arity = "0..1") int index2 = -1;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult result = cmd.parseArgs("-x", "xval", "0", "1");

    assertSame(result.commandSpec().findOption("-x"), result.tentativeMatch.get(0));
    assertSame(result.originalArgs().get(1), result.tentativeMatch.get(1));
    assertSame(result.commandSpec().positionalParameters().get(0), result.tentativeMatch.get(2));
    assertSame(result.commandSpec().positionalParameters().get(1), result.tentativeMatch.get(3));

    List<PositionalParamSpec> all = cmd.getCommandSpec().positionalParameters();
    assertTrue(result.hasMatchedPositional(all.get(0)));
    assertTrue(result.hasMatchedPositional(all.get(1)));
    assertFalse(result.hasMatchedPositional(all.get(2)));
}
 
Example #8
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatchedPositionals_ReturnsOnlyMatchedPositionals() {
    class App {
        @Option(names = "-x") String x;
        @Parameters(index = "0", arity = "0..1") int index0 = -1;
        @Parameters(index = "1", arity = "0..1") int index1 = -1;
        @Parameters(index = "2", arity = "0..1") int index2 = -1;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("-x", "xval", "0", "1");

    List<PositionalParamSpec> all = cmd.getCommandSpec().positionalParameters();
    assertEquals(3, all.size());

    List<PositionalParamSpec> found = parseResult.matchedPositionals();
    assertEquals(2, found.size());
    assertSame(all.get(0), found.get(0));
    assertSame(all.get(1), found.get(1));

    assertSame(parseResult.matchedPositional(0), found.get(0));
    assertSame(parseResult.matchedPositional(1), found.get(1));
    assertNull(parseResult.matchedPositional(2));
}
 
Example #9
Source File: FileSystemCompiler.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Same as main(args) except that exceptions are thrown out instead of causing
 * the VM to exit and the lookup for .groovy files can be controlled
 */
public static void commandLineCompile(String[] args, boolean lookupUnnamedFiles) throws Exception {
    CompilationOptions options = new CompilationOptions();
    CommandLine parser = configureParser(options);
    ParseResult parseResult = parser.parseArgs(args);
    if (CommandLine.printHelpIfRequested(parseResult)) {
        return;
    }
    displayStackTraceOnError = options.printStack;
    CompilerConfiguration configuration = options.toCompilerConfiguration();

    // Load the file name list
    String[] filenames = options.generateFileNames();
    boolean fileNameErrors = filenames == null;
    if (!fileNameErrors && (filenames.length == 0)) {
        parser.usage(System.err);
        return;
    }

    fileNameErrors = fileNameErrors && !validateFiles(filenames);

    if (!fileNameErrors) {
        doCompilation(configuration, null, filenames, lookupUnnamedFiles);
    }
}
 
Example #10
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 #11
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testOptionSpec_defaultValue_overwritesInitialValue() {
    class Params {
        @Option(names = "-x") int num = 12345;
    }
    CommandLine cmd = new CommandLine(new Params());
    OptionSpec x = cmd.getCommandSpec().posixOptionsMap().get('x').toBuilder().defaultValue("54321").build();

    cmd = new CommandLine(CommandSpec.create().addOption(x));
    ParseResult parseResult = cmd.parseArgs();
    assertFalse(parseResult.hasMatchedOption('x'));
    // TODO this method should be renamed to matchedOptionValue
    assertEquals(Integer.valueOf(-1), parseResult.matchedOptionValue('x', -1));

    // TODO optionValue should return the value of the option, matched or not
    //assertEquals(Integer.valueOf(54321), parseResult.optionValue('x'));
    assertEquals(Integer.valueOf(54321), parseResult.commandSpec().findOption('x').getValue());
}
 
Example #12
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatchedPositional_ReturnsNullForNonMatchedPosition() {
    class App {
        @Parameters(index = "0", arity = "0..1") int index0 = -1;
        @Parameters(index = "1", arity = "0..1") int index1 = -1;
        @Parameters(index = "2", arity = "0..1") int index2 = -1;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("0", "1");

    assertNotNull(parseResult.matchedPositional(0));
    assertNotNull(parseResult.matchedPositional(1));

    assertNull(parseResult.matchedPositional(2));
    assertNull(parseResult.matchedPositional(3));
}
 
Example #13
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testRawPositionalValue_ReturnsNullForNonMatchedPosition() {
    class App {
        @Parameters(index = "0", arity = "0..1") int index0 = -1;
        @Parameters(index = "1", arity = "0..1") int index1 = -1;
        @Parameters(index = "2", arity = "0..1") int index2 = -1;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("0", "1");

    assertEquals("0", parseResult.matchedPositional(0).stringValues().get(0));
    assertEquals("1", parseResult.matchedPositional(1).stringValues().get(0));

    assertNull(parseResult.matchedPositional(2));
    assertNull(parseResult.matchedPositional(3));
}
 
Example #14
Source File: ExampleInterface.java    From picocli with Apache License 2.0 6 votes vote down vote up
private static int execute(String[] args) {
    final CommandLine cmd = new CommandLine(ExampleInterface.class);
    cmd.setExecutionStrategy(new IExecutionStrategy() {
        public int execute(ParseResult parseResult) throws ExecutionException, ParameterException {
            Integer result = CommandLine.executeHelpRequest(parseResult);
            if (result != null) {
                return result;
            }
            // invoke the business logic
            ExampleInterface exampleInterface = cmd.getCommand();
            businessLogic(exampleInterface);
            return cmd.getCommandSpec().exitCodeOnSuccess();
        }
    });
    return cmd.execute(args);
}
 
Example #15
Source File: ExampleInterface.java    From picocli with Apache License 2.0 6 votes vote down vote up
private static int execute(String[] args) {
    final CommandLine cmd = new CommandLine(ExampleInterface.class);
    cmd.setExecutionStrategy(new IExecutionStrategy() {
        public int execute(ParseResult parseResult) throws ExecutionException, ParameterException {
            Integer result = CommandLine.executeHelpRequest(parseResult);
            if (result != null) {
                return result;
            }
            // invoke the business logic
            ExampleInterface exampleInterface = cmd.getCommand();
            businessLogic(exampleInterface);
            return cmd.getCommandSpec().exitCodeOnSuccess();
        }
    });
    return cmd.execute(args);
}
 
Example #16
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testRawPositionalValueWithDefault_ReturnsDefaultForNonMatchedPosition() {
    class App {
        @Parameters(index = "0", arity = "0..1") int index0 = -1;
        @Parameters(index = "1", arity = "0..1") int index1 = -1;
        @Parameters(index = "2", arity = "0..1") int index2 = -1;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("0", "1");

    assertEquals(Integer.valueOf(0), parseResult.matchedPositionalValue(0, Integer.valueOf(123)));
    assertEquals(Integer.valueOf(1), parseResult.matchedPositionalValue(1, Integer.valueOf(456)));

    assertEquals(Integer.valueOf(123), parseResult.matchedPositionalValue(2, Integer.valueOf(123)));
    assertEquals(Integer.valueOf(456), parseResult.matchedPositionalValue(3, Integer.valueOf(456)));
}
 
Example #17
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatchedPositionalValue() {
    class App {
        @Parameters(index = "0", arity = "0..1") int index0 = -1;
        @Parameters(index = "1", arity = "0..1") int index1 = -1;
        @Parameters(index = "2", arity = "0..1") int index2 = -1;
    }
    App app = new App();
    CommandLine cmd = new CommandLine(app);
    ParseResult parseResult = cmd.parseArgs("0", "1");
    assertEquals( 0, app.index0);
    assertEquals( 1, app.index1);
    assertEquals(-1, app.index2);

    List<PositionalParamSpec> found = parseResult.matchedPositionals();
    assertEquals(2, found.size());
    assertEquals(Integer.valueOf(0), parseResult.matchedPositionalValue(0, 0));
    assertEquals(Integer.valueOf(1), parseResult.matchedPositionalValue(1, 1));
    assertNull(parseResult.matchedPositionalValue(2, null));
}
 
Example #18
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsUsageHelpRequested() {
    @Command(mixinStandardHelpOptions = true)
    class App {
        @Option(names = "-x") String x;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("-h");
    assertTrue(parseResult.isUsageHelpRequested());
    assertFalse(parseResult.isVersionHelpRequested());

    assertSame(cmd.getCommandSpec().optionsMap().get("-h"), parseResult.matchedOption('h'));

    assertTrue(parseResult.unmatched().isEmpty());
    assertTrue(parseResult.matchedPositionals().isEmpty());
}
 
Example #19
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testHasMatchedOptionByName_VariousPrefixes() {
    class App {
        @Option(names = {"-x", "++XX", "/XXX"}) String[] x;
        @Option(names = "-y") String y;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult result = cmd.parseArgs("-x", "value1", "-x", "value2");
    assertTrue(result.hasMatchedOption("x"));
    assertTrue(result.hasMatchedOption("-x"));
    assertTrue(result.hasMatchedOption("XX"));
    assertTrue(result.hasMatchedOption("++XX"));
    assertTrue(result.hasMatchedOption("XXX"));
    assertTrue(result.hasMatchedOption("/XXX"));

    assertFalse(result.hasMatchedOption("y"));
    assertFalse(result.hasMatchedOption("-y"));

    assertSame(result.commandSpec().findOption("-x"), result.tentativeMatch.get(0));
    assertSame(result.originalArgs().get(1), result.tentativeMatch.get(1));
    assertSame(result.commandSpec().findOption("-x"), result.tentativeMatch.get(2));
    assertSame(result.originalArgs().get(3), result.tentativeMatch.get(3));
}
 
Example #20
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatchedOptions_ReturnsOnlyMatchedOptions() {
    class App {
        @Option(names = "-a", arity = "0..1") String a;
        @Option(names = "-b", arity = "0..1") String b;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("-a");

    List<OptionSpec> options = parseResult.matchedOptions();
    assertEquals(1, options.size());

    Map<String, OptionSpec> optionsMap = cmd.getCommandSpec().optionsMap();
    assertTrue(parseResult.hasMatchedOption(optionsMap.get("-a")));
    assertFalse(parseResult.hasMatchedOption(optionsMap.get("-b")));
}
 
Example #21
Source File: SubcommandTests.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test // https://github.com/remkop/picocli/issues/990
public void testIssue990_OptionsInSubcommandsNotResetToTheirInitialValue() {
    CommandLine cmd = new CommandLine(new Top990());
    ParseResult result1 = cmd.parseArgs("-a=1 sub -b=2 subsub -c=3".split(" "));
    assertEquals(Integer.valueOf(1), result1.matchedOptionValue("-a", 0));
    assertEquals(Integer.valueOf(2), result1.subcommand().matchedOptionValue("-b", 0));
    assertEquals(Integer.valueOf(3), result1.subcommand().subcommand().matchedOptionValue("-c", 0));
    assertEquals(1, ((Top990)result1.commandSpec().userObject()).a);
    assertEquals(2, ((Sub990)result1.subcommand().commandSpec().userObject()).b);
    assertEquals(3, ((SubSub990)result1.subcommand().subcommand().commandSpec().userObject()).c);

    // now check that option values are reset to their default on the 2nd invocation
    ParseResult result2 = cmd.parseArgs("sub subsub".split(" "));
    assertEquals(-11, ((Top990)result2.commandSpec().userObject()).a);
    assertEquals(-22, ((Sub990)result2.subcommand().commandSpec().userObject()).b);
    assertEquals(-33, ((SubSub990)result2.subcommand().subcommand().commandSpec().userObject()).c);
}
 
Example #22
Source File: AtFileTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testAtFileExpandedArgsParsed() {
    class App {
        @Option(names = "-v")
        private boolean verbose;

        @Parameters
        private List<String> files;
    }
    File file = findFile("/argfile1.txt");
    if (!file.getAbsolutePath().startsWith(System.getProperty("user.dir"))) {
        return;
    }
    String relative = file.getAbsolutePath().substring(System.getProperty("user.dir").length());
    if (relative.startsWith(File.separator)) {
        relative = relative.substring(File.separator.length());
    }
    CommandLine commandLine = new CommandLine(new App());
    ParseResult parseResult = commandLine.parseArgs(new String[] {"@" + relative});

    assertEquals(Arrays.asList("1111", "-v", "2222", ";3333"), parseResult.expandedArgs());
}
 
Example #23
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatchedOption_ReturnsOnlyMatchedOptions() {
    class App {
        @Option(names = "-a", arity = "0..1") String a;
        @Option(names = "-b", arity = "0..1") String b;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("-a");

    assertNotNull(parseResult.matchedOption('a'));
    assertNotNull(parseResult.matchedOption("a"));
    assertNotNull(parseResult.matchedOption("-a"));

    assertNull(parseResult.matchedOption('b'));
    assertNull(parseResult.matchedOption("b"));
    assertNull(parseResult.matchedOption("-b"));
}
 
Example #24
Source File: MakeArgOrderSignificant.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Override
public Integer call() throws Exception {
    // Get the ParseResult. This is also the object returned by
    // the CommandLine.parseArgs method, but the CommandLine.execute method
    // is more convenient to use (see https://picocli.info/#_diy_command_execution),
    // so we get the parse result from the @Spec.
    ParseResult pr = spec.commandLine().getParseResult();

    // The ParseResult.matchedArgs method returns the matched options and
    // positional parameters, in order they were matched on the command line.
    List<ArgSpec> argSpecs = pr.matchedArgs();

    if (argSpecs.get(0).isPositional()) {
        System.out.println("The first arg is a positional parameter: treating all args as Strings...");
        // ...
    } else { // argSpecs.get(0).isOption()
        System.out.println("The first arg is an option");
        boolean isDebug = spec.findOption("--debug").equals(argSpecs.get(0));
        System.out.printf("The first arg %s --debug%n", isDebug ? "is" : "is not");
        if (isDebug) {
            // do debuggy stuff...
        }
    }

    return 0;
}
 
Example #25
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue829NPE_inSubcommandWithArgGroup() {
    //TestUtil.setTraceLevel("DEBUG");
    ParseResult parseResult = new CommandLine(new Issue829TopCommand()).parseArgs("-x=1", "sub", "-y=2");
    assertEquals(1, ((Issue829TopCommand)parseResult.commandSpec().userObject()).group.x);

    Issue829Subcommand sub = (Issue829Subcommand) parseResult.subcommand().commandSpec().userObject();
    assertEquals(0, sub.group.get(0).x);
    assertEquals(2, sub.group.get(0).y);

    new CommandLine(new Issue829TopCommand()).parseArgs("sub2", "-y=3");
}
 
Example #26
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseResult_matchedOptionsSet() {
    @Command(mixinStandardHelpOptions = true) class A {}
    ParseResult pr = new CommandLine(new A()).parseArgs("--help", "--version");
    Set<OptionSpec> matched = pr.matchedOptionsSet();
    assertEquals(2, matched.size());
    assertTrue(matched.contains(pr.commandSpec().findOption("--help")));
    assertTrue(matched.contains(pr.commandSpec().findOption("--version")));
}
 
Example #27
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test(expected = ClassCastException.class)
public void testOptionValueWrongType() {
    class App {
        @Option(names = "-x") int[] x;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("-x", "123", "-x", "456");
    long[] wrongType = {123L, 456L};
    assertArrayEquals(wrongType, parseResult.matchedOptionValue("x", wrongType));
}
 
Example #28
Source File: ExecutionStrategyWithExecutionResult.java    From picocli with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) {

        CommandSpec spec = CommandSpec.create();
        spec.mixinStandardHelpOptions(true);
        spec.addOption(OptionSpec.builder("-c", "--count")
                .paramLabel("COUNT")
                .type(int.class)
                .description("number of times to execute").build());
        spec.addPositional(PositionalParamSpec.builder()
                .paramLabel("FILES")
                .type(List.class)
                .auxiliaryTypes(File.class)
                .description("The files to process").build());
        CommandLine commandLine = new CommandLine(spec);

        class Handler implements IExecutionStrategy {
            @Override
            public int execute(ParseResult pr) {
                int count = pr.matchedOptionValue('c', 1);
                List<File> files = pr.matchedPositionalValue(0, Collections.<File>emptyList());
                for (File f : files) {
                    for (int i = 0; i < count; i++) {
                        System.out.println(i + " " + f.getName());
                    }
                }
                pr.commandSpec().commandLine().setExecutionResult(files.size());
                return ExitCode.OK;
            }
        }

        commandLine.setExecutionStrategy(new Handler());
        commandLine.execute(args);
        int processed = commandLine.getExecutionResult();
    }
 
Example #29
Source File: ModelParseResultTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testMatchedOption_returnsNullForNonMatchedOption() {
    class App {
        @Option(names = {"-x", "++XX", "/XXX"}) String[] x;
        @Option(names = "-y") String y;
    }
    CommandLine cmd = new CommandLine(new App());
    ParseResult parseResult = cmd.parseArgs("-x", "value1", "-x", "value2");
    assertNull(parseResult.matchedOption('y'));
    assertNull(parseResult.matchedOption("y"));
}
 
Example #30
Source File: ExecutionExceptionHandlerDemo.java    From picocli with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    IExecutionExceptionHandler errorHandler = new IExecutionExceptionHandler() {
        public int handleExecutionException(Exception ex,
                                            CommandLine commandLine,
                                            ParseResult parseResult) {
            commandLine.getErr().println(ex.getMessage());
            commandLine.usage(commandLine.getErr());
            return commandLine.getCommandSpec().exitCodeOnExecutionException();
        }
    };
    int exitCode = new CommandLine(new ExecutionExceptionHandlerDemo())
            .setExecutionExceptionHandler(errorHandler)
            .execute(args);
}