picocli.CommandLine.Model.OptionSpec Java Examples

The following examples show how to use picocli.CommandLine.Model.OptionSpec. 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 testDontClearInitialValueBeforeParseIfInitialValueFalse() {
    CommandSpec cmd = CommandSpec.create();
    Map<String, String> map = new HashMap<String, String>();
    map.put("ABC", "XYZ");
    cmd.addOption(OptionSpec.builder("-x").type(Map.class).initialValue(map).hasInitialValue(true).build());

    CommandLine cl = new CommandLine(cmd);
    cl.parseArgs("-x", "A=1", "-x", "B=2", "-x", "C=3");
    Map<String, String> expected = new LinkedHashMap<String, String>();
    expected.put("A", "1");
    expected.put("B", "2");
    expected.put("C", "3");
    assertEquals(expected, cmd.findOption("x").getValue());

    cl.parseArgs("-x", "D=4", "-x", "E=5");
    expected = new LinkedHashMap<String, String>();
    expected.put("D", "4");
    expected.put("E", "5");
    assertEquals(expected, cmd.findOption("x").getValue());

    cl.parseArgs();
    expected = new LinkedHashMap<String, String>();
    expected.put("ABC", "XYZ");
    assertEquals(expected, cmd.findOption("x").getValue());
}
 
Example #2
Source File: OptionalOptionParamDemo.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Override
public void consumeParameters(Stack<String> args, ArgSpec argSpec, CommandSpec commandSpec) {
    String arg = args.pop();
    try {
        int port = Integer.parseInt(arg);
        argSpec.setValue(port);
    } catch (Exception ex) {
        String fallbackValue = (argSpec.isOption()) ? ((OptionSpec) argSpec).fallbackValue() : null;
        try {
            int fallbackPort = Integer.parseInt(fallbackValue);
            argSpec.setValue(fallbackPort);
        } catch (Exception badFallbackValue) {
            throw new InitializationException("FallbackValue for --debug must be an int", badFallbackValue);
        }
        args.push(arg); // put it back
    }
}
 
Example #3
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsSubgroupOf_TrueIfChild() {
    ArgGroupSpec subsub = ArgGroupSpec.builder()
            .addArg(OptionSpec.builder("-a").required(true).build()).build();
    ArgGroupSpec sub = ArgGroupSpec.builder()
            .addArg(OptionSpec.builder("-x").required(true).build())
            .addArg(OptionSpec.builder("-y").required(true).build())
            .addSubgroup(subsub).build();
    ArgGroupSpec top = ArgGroupSpec.builder()
            .addArg(OptionSpec.builder("-z").required(true).build())
            .addSubgroup(sub).build();

    assertTrue(sub.isSubgroupOf(top));
    assertTrue(subsub.isSubgroupOf(sub));
    assertTrue(subsub.isSubgroupOf(top));

    assertFalse(top.isSubgroupOf(sub));
    assertFalse(top.isSubgroupOf(subsub));
    assertFalse(sub.isSubgroupOf(subsub));
}
 
Example #4
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubcommandNameNotOverwrittenWhenAddedToParent() {
    CommandSpec toplevel = CommandSpec.create();
    toplevel.addOption(OptionSpec.builder("-o").description("o option").build());

    CommandSpec sub = CommandSpec.create().name("SOMECOMMAND");
    sub.addOption(OptionSpec.builder("-x").description("x option").build());

    CommandLine commandLine = new CommandLine(toplevel);
    CommandLine subCommandLine = new CommandLine(sub);
    assertEquals("SOMECOMMAND", sub.name());
    assertEquals("SOMECOMMAND", subCommandLine.getCommandName());

    commandLine.addSubcommand("sub", subCommandLine);
    assertEquals("SOMECOMMAND", sub.name());
    assertEquals("SOMECOMMAND", subCommandLine.getCommandName());

    subCommandLine.usage(System.out);

    String expected = String.format("" +
            "Usage: <main class> SOMECOMMAND [-x]%n" +
            "  -x     x option%n");
    assertEquals(expected, systemOutRule.getLog());
}
 
Example #5
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testSynopsisMixOptionsPositionals() {
    ArgGroupSpec.Builder builder = ArgGroupSpec.builder()
            .addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG1").required(true).build())
            .addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG2").required(true).build())
            .addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG3").required(true).build())
            .addArg(OptionSpec.builder("-a").required(true).build())
            .addArg(OptionSpec.builder("-b").required(true).build())
            .addArg(OptionSpec.builder("-c").required(true).build());
    assertEquals("[ARG1 | ARG2 | ARG3 | -a | -b | -c]", builder.build().synopsis());

    builder.multiplicity("1");
    assertEquals("(ARG1 | ARG2 | ARG3 | -a | -b | -c)", builder.build().synopsis());

    builder.exclusive(false);
    assertEquals("(ARG1 ARG2 ARG3 -a -b -c)", builder.build().synopsis());

    builder.multiplicity("0..1");
    assertEquals("[ARG1 ARG2 ARG3 -a -b -c]", builder.build().synopsis());
}
 
Example #6
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testOptionClearCustomSetterBeforeParse() {
    CommandSpec cmd = CommandSpec.create();
    final List<Object> values = new ArrayList<Object>();
    ISetter setter = new ISetter() {
        public <T> T set(T value) {
            values.add(value);
            return null;
        }
    };
    cmd.addOption(OptionSpec.builder("-x").type(String.class).setter(setter).build());

    CommandLine cl = new CommandLine(cmd);
    assertTrue(values.isEmpty());
    cl.parseArgs("-x", "1");
    assertEquals(2, values.size());
    assertEquals(null, values.get(0));
    assertEquals("1", values.get(1));

    values.clear();
    cl.parseArgs("-x", "2");
    assertEquals(2, values.size());
    assertEquals(null, values.get(0));
    assertEquals("2", values.get(1));
}
 
Example #7
Source File: ModelUsageMessageSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testModelUsageHelpWithCustomSeparator() {
    CommandSpec spec = CommandSpec.create();
    spec.addOption(OptionSpec.builder("-h", "--help").usageHelp(true).description("show help and exit").build());
    spec.addOption(OptionSpec.builder("-V", "--version").versionHelp(true).description("show help and exit").build());
    spec.addOption(OptionSpec.builder("-c", "--count").paramLabel("COUNT").arity("1").type(int.class).description("number of times to execute").build());
    spec.addOption(OptionSpec.builder("-f", "--fix").paramLabel("FIXED(=BOOLEAN)").arity("1").hideParamSyntax(true).required(true).description("run with fixed option").build());
    CommandLine commandLine = new CommandLine(spec).setSeparator(" ");
    String actual = usageString(commandLine, CommandLine.Help.Ansi.OFF);
    String expected = String.format("" +
            "Usage: <main class> [-hV] [-c COUNT] -f FIXED(=BOOLEAN)%n" +
            "  -c, --count COUNT   number of times to execute%n" +
            "  -f, --fix FIXED(=BOOLEAN)%n" +
            "                      run with fixed option%n" +
            "  -h, --help          show help and exit%n" +
            "  -V, --version       show help and exit%n");
    assertEquals(expected, actual);
}
 
Example #8
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 #9
Source File: CommandLineTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInterpreterProcessClusteredShortOptions() throws Exception {
    Class c = Class.forName("picocli.CommandLine$Interpreter");
    Method processClusteredShortOptions = c.getDeclaredMethod("processClusteredShortOptions",
            Collection.class, Set.class, String.class, boolean.class, Stack.class);
    processClusteredShortOptions.setAccessible(true);

    CommandSpec spec = CommandSpec.create();
    spec.addOption(OptionSpec.builder("-x").arity("0").build());
    spec.parser().trimQuotes(true);
    CommandLine cmd = new CommandLine(spec);
    Object interpreter = TestUtil.interpreter(cmd);

    Stack<String> stack = new Stack<String>();
    String arg = "-xa";
    processClusteredShortOptions.invoke(interpreter, new ArrayList<ArgSpec>(), new HashSet<String>(), arg, true, stack);
    assertEquals(true, cmd.getParseResult().matchedOptionValue('x', null));
}
 
Example #10
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 #11
Source File: CustomOptionListAndSynopsis.java    From picocli with Apache License 2.0 6 votes vote down vote up
public String render(CommandLine.Help help) {

            // building a custom synopsis is more complex;
            // we subclass Help here so we can invoke some protected methods
            class HelpHelper extends CommandLine.Help {
                public HelpHelper(CommandSpec commandSpec, ColorScheme colorScheme) {
                    super(commandSpec, colorScheme);
                }
                String buildSynopsis() {
                    // customize the list of options to show in the synopsis
                    List<OptionSpec> myOptions = filter(help.commandSpec().options());

                    // and build up the synopsis text with our customized options list...
                    Set<ArgSpec> argsInGroups = new HashSet<ArgSpec>();
                    Text groupsText = createDetailedSynopsisGroupsText(argsInGroups);
                    Text optionText = createDetailedSynopsisOptionsText(argsInGroups, myOptions, CommandLine.Help.createShortOptionArityAndNameComparator(), true);
                    Text endOfOptionsText = createDetailedSynopsisEndOfOptionsText();
                    Text positionalParamText = createDetailedSynopsisPositionalsText(argsInGroups);
                    Text commandText = createDetailedSynopsisCommandText();

                    return makeSynopsisFromParts(help.synopsisHeadingLength(), optionText, groupsText, endOfOptionsText, positionalParamText, commandText);
                }
            }
            // and delegate the work to our helper subclass
            return new HelpHelper(help.commandSpec(), help.colorScheme()).buildSynopsis();
        }
 
Example #12
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testResemblesOption_WithOptionsDash() {
    CommandSpec spec = CommandSpec.wrapWithoutInspection(null);
    spec.addOption(OptionSpec.builder("-x").build());

    spec.parser().unmatchedOptionsArePositionalParams(false);
    assertFalse(spec.resemblesOption("blah", null));

    System.setProperty("picocli.trace", "DEBUG");
    Tracer tracer = new Tracer();
    System.clearProperty("picocli.trace");
    assertFalse(spec.resemblesOption("blah", tracer));
    assertTrue(spec.resemblesOption("-a", tracer));
    assertFalse(spec.resemblesOption("/a", tracer));

    Tracer tracer2 = new Tracer();
    assertFalse(spec.resemblesOption("blah", tracer2));
    assertTrue(spec.resemblesOption("-a", tracer));
    assertFalse(spec.resemblesOption("/a", tracer));
}
 
Example #13
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testClearArrayOptionOldValueBeforeParse() {
    CommandSpec cmd = CommandSpec.create();
    cmd.addOption(OptionSpec.builder("-x").arity("2..3").initialValue(new String[] {"ABC"}).build());

    CommandLine cl = new CommandLine(cmd);
    cl.parseArgs("-x", "1", "2", "3");
    assertArrayEquals(new String[] {"1", "2", "3"}, (String[]) cmd.findOption("x").getValue());
    assertArrayEquals(new String[] {"1", "2", "3"}, (String[]) cmd.findOption('x').getValue());

    cl.parseArgs("-x", "4", "5");
    assertArrayEquals(new String[] {"4", "5"}, (String[]) cmd.findOption("x").getValue());
    assertArrayEquals(new String[] {"4", "5"}, (String[]) cmd.findOption('x').getValue());

    cl.parseArgs();
    assertArrayEquals(new String[] {"ABC"}, (String[]) cmd.findOption("x").getValue());
    assertArrayEquals(new String[] {"ABC"}, (String[]) cmd.findOption('x').getValue());
}
 
Example #14
Source File: PicoCLIOptionsImpl.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public void addPicoCLIOptions(final String namespace, final Object optionObject) {
  final String pluginPrefix = "--plugin-" + namespace + "-";
  final String unstablePrefix = "--Xplugin-" + namespace + "-";
  final CommandSpec mixin = CommandSpec.forAnnotatedObject(optionObject);
  boolean badOptionName = false;

  for (final OptionSpec optionSpec : mixin.options()) {
    for (final String optionName : optionSpec.names()) {
      if (!optionName.startsWith(pluginPrefix) && !optionName.startsWith(unstablePrefix)) {
        badOptionName = true;
        LOG.error(
            "Plugin option {} did not have the expected prefix of {}", optionName, pluginPrefix);
      }
    }
  }
  if (badOptionName) {
    throw new RuntimeException("Error loading CLI options");
  } else {
    commandLine.getCommandSpec().addMixin("Plugin " + namespace, mixin);
  }
}
 
Example #15
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllOptionsNested() {
    class Nested {
        @ArgGroup(exclusive = false, multiplicity = "0..*")
        List<Outer1027> outers;
    }

    List<ArgGroupSpec> argGroupSpecs = new CommandLine(new Nested()).getCommandSpec().argGroups();
    assertEquals(1, argGroupSpecs.size());
    ArgGroupSpec group = argGroupSpecs.get(0);
    List<OptionSpec> options = group.options();
    assertEquals(1, options.size());
    assertEquals("-x", options.get(0).shortestName());

    List<OptionSpec> allOptions = group.allOptionsNested();
    assertEquals(2, allOptions.size());
    assertEquals("-x", allOptions.get(0).shortestName());
    assertEquals("-y", allOptions.get(1).shortestName());
}
 
Example #16
Source File: ArgGroupTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testCannotAddSameGroupToCommandMultipleTimes() {
    CommandSpec spec = CommandSpec.create();

    ArgGroupSpec cooccur = ArgGroupSpec.builder()
            .addArg(OptionSpec.builder("-z").required(true).build()).build();

    spec.addArgGroup(cooccur);
    try {
        spec.addArgGroup(cooccur);
        fail("Expected exception");
    } catch (InitializationException ex) {
        assertEquals("The specified group [-z] has already been added to the <main class> command.", ex.getMessage());
    }
}
 
Example #17
Source File: AutoCompleteTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testBashify() {
    CommandSpec cmd = CommandSpec.create().addOption(
            OptionSpec.builder("-x")
                    .type(String.class)
                    .paramLabel("_A\tB C")
                    .completionCandidates(Arrays.asList("1")).build());
    String actual = AutoComplete.bash("bashify", new CommandLine(cmd));
    String expected = format(loadTextFromClasspath("/bashify_completion.bash"), CommandLine.VERSION);
    assertEquals(expected, actual);
}
 
Example #18
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiValueOptionWithArray() {
    CommandSpec spec = CommandSpec.create();
    OptionSpec option = OptionSpec.builder("-c", "--count").arity("3").type(int[].class).build();
    assertTrue(option.isMultiValue());

    spec.addOption(option);
    CommandLine commandLine = new CommandLine(spec);
    commandLine.parseArgs("-c", "1", "2", "3");
    assertArrayEquals(new int[] {1, 2, 3}, (int[]) spec.optionsMap().get("-c").getValue());
}
 
Example #19
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionSpec_setsDefaultValue_ifNotMatched() {
    CommandSpec cmd = CommandSpec.create().addOption(OptionSpec.builder("-x").defaultValue("123").type(int.class).build());

    ParseResult parseResult = new CommandLine(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(123), parseResult.optionValue('x'));
    assertEquals(Integer.valueOf(123), parseResult.commandSpec().findOption('x').getValue());
}
 
Example #20
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionSpec_DefaultValue_array_replacedByCommandLineValue() {
    CommandSpec cmd = CommandSpec.create().addOption(OptionSpec
            .builder("-x").defaultValue("1,2,3").splitRegex(",").type(int[].class).build());

    ParseResult parseResult = new CommandLine(cmd).parseArgs("-x", "4,5,6");
    assertArrayEquals(new int[]{4, 5, 6}, parseResult.matchedOptionValue('x', new int[0]));
}
 
Example #21
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionSpec_DefaultValue_list_replacedByCommandLineValue() {
    CommandSpec cmd = CommandSpec.create().addOption(OptionSpec
            .builder("-x").defaultValue("1,2,3").splitRegex(",").type(List.class).auxiliaryTypes(Integer.class).build());

    ParseResult parseResult = new CommandLine(cmd).parseArgs("-x", "4,5,6");
    assertEquals(Arrays.asList(4, 5, 6), parseResult.matchedOptionValue('x', Collections.emptyList()));
}
 
Example #22
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionSpec_DefaultValue_map_replacedByCommandLineValue() {
    CommandSpec cmd = CommandSpec.create().add(OptionSpec
            .builder("-x").defaultValue("1=A,2=B,3=C").splitRegex(",").type(Map.class).auxiliaryTypes(Integer.class, String.class).build());

    ParseResult parseResult = new CommandLine(cmd).parseArgs("-x", "4=X,5=Y,6=Z");
    Map<Integer, String> expected = new HashMap<Integer, String>();
    expected.put(4, "X");
    expected.put(5, "Y");
    expected.put(6, "Z");
    assertEquals(expected, parseResult.matchedOptionValue('x', Collections.emptyMap()));
}
 
Example #23
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleUsageHelpOptions() {
    setTraceLevel("WARN");
    CommandSpec cmd = CommandSpec.create()
            .add(OptionSpec.builder("-x").type(boolean.class).usageHelp(true).build())
            .add(OptionSpec.builder("-h").type(boolean.class).usageHelp(true).build());

    assertEquals("", systemErrRule.getLog());
    systemErrRule.clearLog();
    new CommandLine(cmd);
    assertEquals("", systemOutRule.getLog());
    assertEquals(String.format("[picocli WARN] Multiple options [-x, -h] are marked as 'usageHelp=true'. Usually a command has only one --help option that triggers display of the usage help message. Alternatively, consider using @Command(mixinStandardHelpOptions = true) on your command instead.%n"), systemErrRule.getLog());
}
 
Example #24
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonBooleanVersionHelpOptions() {
    CommandSpec cmd = CommandSpec.create().add(OptionSpec.builder("-x").type(int.class).versionHelp(true).build());
    try {
        new CommandLine(cmd);
    } catch (InitializationException ex) {
        assertEquals("Non-boolean options like [-x] should not be marked as 'versionHelp=true'. Usually a command has one --version boolean flag that triggers display of the version information. Alternatively, consider using @Command(mixinStandardHelpOptions = true) on your command instead.", ex.getMessage());
    }
}
 
Example #25
Source File: BasicResultProcessing.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);

        try {
            ParseResult pr = commandLine.parseArgs(args);
            if (CommandLine.printHelpIfRequested(pr)) { return; }

            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());
                }
            }

        } catch (ParameterException ex) {
            System.err.println(ex.getMessage());
            ex.getCommandLine().usage(System.err);
        }
    }
 
Example #26
Source File: ModelCommandSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiValueOptionWithMapAndAuxTypes() {
    CommandSpec spec = CommandSpec.create();
    OptionSpec option = OptionSpec.builder("-c", "--count").arity("3").type(Map.class).auxiliaryTypes(Integer.class, Double.class).build();
    assertTrue(option.isMultiValue());

    spec.addOption(option);
    CommandLine commandLine = new CommandLine(spec);
    commandLine.parseArgs("-c", "1=1.0", "2=2.0", "3=3.0");
    Map<Integer, Double> expected = new LinkedHashMap<Integer, Double>();
    expected.put(1, 1.0);
    expected.put(2, 2.0);
    expected.put(3, 3.0);
    assertEquals(expected, spec.optionsMap().get("-c").getValue());
}
 
Example #27
Source File: PicocliCommands.java    From picocli with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param args
 * @return command description for JLine TailTipWidgets to be displayed in terminal status bar.
 */
@Override
public CmdDesc commandDescription(List<String> args) {
    CommandLine sub = findSubcommandLine(args, args.size());
    if (sub == null) {
        return null;
    }
    CommandSpec spec = sub.getCommandSpec();
    Help cmdhelp= new picocli.CommandLine.Help(spec);
    List<AttributedString> main = new ArrayList<>();
    Map<String, List<AttributedString>> options = new HashMap<>();
    String synopsis = AttributedString.stripAnsi(spec.usageMessage().sectionMap().get("synopsis").render(cmdhelp).toString());
    main.add(HelpException.highlightSyntax(synopsis.trim(), HelpException.defaultStyle()));
    // using JLine help highlight because the statement below does not work well...
    //        main.add(new AttributedString(spec.usageMessage().sectionMap().get("synopsis").render(cmdhelp).toString()));
    for (OptionSpec o : spec.options()) {
        String key = Arrays.stream(o.names()).collect(Collectors.joining(" "));
        List<AttributedString> val = new ArrayList<>();
        for (String d:  o.description()) {
            val.add(new AttributedString(d));
        }
        if (o.arity().max() > 0) {
            key += "=" + o.paramLabel();
        }
        options.put(key, val);
    }
    return new CmdDesc(main, ArgDesc.doArgNames(Arrays.asList("")), options);
}
 
Example #28
Source File: ManPageGenerator.java    From picocli with Apache License 2.0 5 votes vote down vote up
private static Comparator<OptionSpec> createOrderComparatorIfNecessary(List<OptionSpec> options) {
    for (OptionSpec option : options) {
        if (option.order() != -1/*OptionSpec.DEFAULT_ORDER*/) {
            return new SortByOrder<OptionSpec>();
        }
    }
    return null;
}
 
Example #29
Source File: PropertiesDefaultProviderTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyFile() throws Exception {
    File temp = File.createTempFile("MyCommand", ".properties");
    FileWriter fw = new FileWriter(temp);
    fw.flush();
    fw.close();

    PropertiesDefaultProvider provider = new PropertiesDefaultProvider(temp);
    String actual = provider.defaultValue(OptionSpec.builder("-x").build());
    assertNull(actual);
}
 
Example #30
Source File: ModelArgSpecTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testArgSpecBuilderSplitRegexAndSplitRegexSynopsisLabel() {
    Builder builder = OptionSpec.builder("-x").type(String[].class).splitRegex("#").splitRegexSynopsisLabel(";");
    assertEquals("split regex synopsis label", ";", builder.splitRegexSynopsisLabel());
    assertEquals("split regex synopsis label", ";", builder.build().splitRegexSynopsisLabel());

    PositionalParamSpec.Builder pb = PositionalParamSpec.builder().type(String[].class).splitRegex("#").splitRegexSynopsisLabel(";");
    assertEquals("split regex synopsis label", ";", pb.splitRegexSynopsisLabel());
    assertEquals("split regex synopsis label", ";", pb.build().splitRegexSynopsisLabel());
}