picocli.CommandLine.Model.ArgSpec Java Examples
The following examples show how to use
picocli.CommandLine.Model.ArgSpec.
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: ReflectionConfigGenerator.java From picocli with Apache License 2.0 | 6 votes |
private void visitGroupSpec(ArgGroupSpec group) throws Exception { IScope scope = group.scope(); if (scope != null) { Object scopeValue = scope.get(); if (scopeValue != null) { getOrCreateClass(scopeValue.getClass()); } } visitGetter(group.getter()); visitSetter(group.setter()); for (ArgSpec argSpec : group.args()) { visitArgSpec(argSpec); } for (ArgGroupSpec subGroup : group.subgroups()) { visitGroupSpec(subGroup); } }
Example #2
Source File: ParameterConsumerTest.java From picocli with Apache License 2.0 | 6 votes |
public void consumeParameters(Stack<String> args, ArgSpec argSpec, CommandSpec commandSpec) { List<String> list = argSpec.getValue(); if (list == null) { // may not be needed if the option is always initialized with non-null value list = new ArrayList<String>(); argSpec.setValue(list); } while (!args.isEmpty()) { String arg = args.pop(); list.add(arg); // `find -exec` semantics: stop processing after a ';' or '+' argument if (";".equals(arg) || "+".equals(arg)) { break; } } }
Example #3
Source File: MakeArgOrderSignificant.java From picocli with Apache License 2.0 | 6 votes |
@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 #4
Source File: OptionalOptionParamDemo.java From picocli with Apache License 2.0 | 6 votes |
@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 #5
Source File: OrderedOptionsTest.java From picocli with Apache License 2.0 | 6 votes |
@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 #6
Source File: CommandLineTest.java From picocli with Apache License 2.0 | 6 votes |
@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 #7
Source File: AutoComplete.java From picocli with Apache License 2.0 | 6 votes |
private static Object findCompletionStartPoint(ParseResult parseResult) { List<Object> tentativeMatches = parseResult.tentativeMatch; for (int i = 1; i <= tentativeMatches.size(); i++) { Object found = tentativeMatches.get(tentativeMatches.size() - i); if (found instanceof CommandSpec) { return found; } if (found instanceof ArgSpec) { CommandLine.Range arity = ((ArgSpec) found).arity(); if (i < arity.min()) { return found; // not all parameters have been supplied yet } else { return findCommandFor((ArgSpec) found, parseResult.commandSpec()); } } } return parseResult.commandSpec(); }
Example #8
Source File: AutoComplete.java From Flashtool with GNU General Public License v3.0 | 6 votes |
private static Object findCompletionStartPoint(ParseResult parseResult) { List<Object> tentativeMatches = parseResult.tentativeMatch; for (int i = 1; i <= tentativeMatches.size(); i++) { Object found = tentativeMatches.get(tentativeMatches.size() - i); if (found instanceof CommandSpec) { return found; } if (found instanceof ArgSpec) { CommandLine.Range arity = ((ArgSpec) found).arity(); if (i < arity.min()) { return found; // not all parameters have been supplied yet } else { return findCommandFor((ArgSpec) found, parseResult.commandSpec()); } } } return parseResult.commandSpec(); }
Example #9
Source File: ArgGroupTest.java From picocli with Apache License 2.0 | 6 votes |
@Ignore //https://github.com/remkop/picocli/issues/871 @Test public void testNonExclusiveGroupMustHaveOneRequiredOption() { class MyApp { @ArgGroup(exclusive = false) NonExclusiveGroup871 group; } CommandLine cmd = new CommandLine(new MyApp()); List<ArgGroupSpec> argGroupSpecs = cmd.getCommandSpec().argGroups(); assertEquals(1, argGroupSpecs.size()); int requiredCount = 0; for (ArgSpec arg : argGroupSpecs.get(0).args()) { if (arg.required()) { requiredCount++; } } assertTrue(requiredCount > 0); }
Example #10
Source File: CustomOptionListAndSynopsis.java From picocli with Apache License 2.0 | 6 votes |
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 #11
Source File: AnnotatedCommandSourceGenerator.java From picocli with Apache License 2.0 | 6 votes |
private static String argElementName(ArgSpec argSpec) { Object userObject = argSpec.userObject(); if (userObject instanceof Field) { return ((Field) userObject).getName(); } else if (userObject instanceof MethodParam) { return ((MethodParam) userObject).getName(); } else if (userObject instanceof Method) { return propertyName(((Method) userObject).getName()); } else if (userObject instanceof VariableElement) { return ((VariableElement) userObject).getSimpleName().toString(); } else if (userObject instanceof ExecutableElement) { return propertyName(((ExecutableElement) userObject).getSimpleName().toString()); } else { return userObject + ""; } }
Example #12
Source File: CommandSpecYamlPrinter.java From picocli with Apache License 2.0 | 6 votes |
private void printArg(ArgSpec arg, PrintWriter pw, String indent) { pw.printf("%sdescription: %s%n", indent, Arrays.toString(arg.description())); pw.printf("%sdescriptionKey: '%s'%n", indent, arg.descriptionKey()); pw.printf("%stypeInfo: %s%n", indent, arg.typeInfo()); pw.printf("%sarity: %s%n", indent, arg.arity()); pw.printf("%ssplitRegex: '%s'%n", indent, arg.splitRegex()); pw.printf("%sinteractive: %s%n", indent, arg.interactive()); pw.printf("%srequired: %s%n", indent, arg.required()); pw.printf("%shidden: %s%n", indent, arg.hidden()); pw.printf("%shideParamSyntax: %s%n", indent, arg.hideParamSyntax()); pw.printf("%sdefaultValue: '%s'%n", indent, arg.defaultValue()); pw.printf("%sshowDefaultValue: %s%n", indent, arg.showDefaultValue()); pw.printf("%shasInitialValue: %s%n", indent, arg.hasInitialValue()); pw.printf("%sinitialValue: '%s'%n", indent, arg.initialValue()); pw.printf("%sparamLabel: '%s'%n", indent, arg.paramLabel()); pw.printf("%sconverters: %s%n", indent, Arrays.toString(arg.converters())); pw.printf("%scompletionCandidates: %s%n", indent, iter(arg.completionCandidates())); pw.printf("%sgetter: %s%n", indent, arg.getter()); pw.printf("%ssetter: %s%n", indent, arg.setter()); }
Example #13
Source File: ArgGroupTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testAllOptionsRequiredInExclusiveGroup() { class MyApp { @ArgGroup(exclusive = true) ExclusiveStringOptionGroup871 group; } CommandLine cmd = new CommandLine(new MyApp()); List<ArgGroupSpec> argGroupSpecs = cmd.getCommandSpec().argGroups(); assertEquals(1, argGroupSpecs.size()); for (ArgSpec arg : argGroupSpecs.get(0).args()) { assertTrue(arg.required()); } }
Example #14
Source File: ArgGroupTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testReflection() { class All { @Option(names = "-x", required = true) int x; @Option(names = "-y", required = true) int y; } class App { @ArgGroup All all; } CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this)); CommandSpec spec = cmd.getCommandSpec(); List<ArgGroupSpec> groups = spec.argGroups(); assertEquals(1, groups.size()); ArgGroupSpec group = groups.get(0); assertNotNull(group); List<ArgSpec> options = new ArrayList<ArgSpec>(group.args()); assertEquals(2, options.size()); assertEquals("-x", ((OptionSpec) options.get(0)).shortestName()); assertEquals("-y", ((OptionSpec) options.get(1)).shortestName()); assertNotNull(options.get(0).group()); assertSame(group, options.get(0).group()); assertNotNull(options.get(1).group()); assertSame(group, options.get(1).group()); }
Example #15
Source File: ArgSplitTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testArgSpecSplitValue_RespectsQuotedValuesByDefault() { ParserSpec parser = new ParserSpec(); ArgSpec spec = PositionalParamSpec.builder().type(String[].class).splitRegex(",").build(); String[] actual = spec.splitValue("a,b,\"c,d,e\",f", parser, Range.valueOf("0"), 0); assertArrayEquals(new String[]{"a", "b", "\"c,d,e\"", "f"}, actual); }
Example #16
Source File: ModelArgSpecTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testArgSpecBuilder_parameterConsumerSetter() { IParameterConsumer consumer = new IParameterConsumer() { public void consumeParameters(Stack<String> args, ArgSpec argSpec, CommandSpec commandSpec) { } }; PositionalParamSpec.Builder builder = PositionalParamSpec.builder().parameterConsumer(consumer); assertSame(consumer, builder.parameterConsumer()); }
Example #17
Source File: ModelArgSpecTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testArgSpecBuilderInferLabel() throws Exception{ Method m = ArgSpec.Builder.class.getDeclaredMethod("inferLabel", String.class, String.class, ITypeInfo.class); m.setAccessible(true); assertEquals("<String=String>", m.invoke(null, "", "fieldName", typeInfo(new Class[0]))); assertEquals("<String=String>", m.invoke(null, "", "fieldName", typeInfo(new Class[]{Integer.class}))); assertEquals("<String=String>", m.invoke(null, "", "fieldName", typeInfo(new Class[]{null, Integer.class}))); assertEquals("<String=String>", m.invoke(null, "", "fieldName", typeInfo(new Class[]{Integer.class, null}))); assertEquals("<Integer=Integer>", m.invoke(null, "", "fieldName", typeInfo(new Class[]{Integer.class, Integer.class}))); }
Example #18
Source File: PropertiesDefaultProvider.java From picocli with Apache License 2.0 | 5 votes |
@Override public String defaultValue(ArgSpec argSpec) throws Exception { if (properties == null) { properties = loadProperties(argSpec.command()); } if (properties == null || properties.isEmpty()) { return null; } return argSpec.isOption() ? optionDefaultValue((OptionSpec) argSpec) : positionalDefaultValue((PositionalParamSpec) argSpec); }
Example #19
Source File: DefaultProviderTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testDefaultValueInDescriptionAfterSetProvider() { String expected2 = String.format("" + "Usage: <main class> [OPTIONS] [<paramStringFieldWithoutDefaultNorInitialValue>] [<paramStringFieldWithAnnotatedDefault>] [<paramStringFieldWithInitDefault>]%n" + " [<paramStringFieldWithoutDefaultNorInitialValue>]%n" + " Default: XYZ%n" + " Default: XYZ%n" + " [<paramStringFieldWithAnnotatedDefault>]%n" + " Default: XYZ%n" + " [<paramStringFieldWithInitDefault>]%n" + " Default: XYZ%n" + " -a=<optionStringFieldWithoutDefaultNorInitialValue>%n" + " Default: XYZ%n" + " -b=<optionStringFieldWithAnnotatedDefault>%n" + " Default: XYZ%n" + " -c=<optionStringFieldWithInitDefault>%n" + " Default: XYZ%n" + " Default: XYZ%n" + " -d=<string> Default: XYZ%n"); CommandLine cmd = new CommandLine(App.class); cmd.setDefaultValueProvider(new IDefaultValueProvider() { public String defaultValue(ArgSpec argSpec) throws Exception { return "XYZ"; } }); assertEquals(expected2, cmd.getUsageMessage(CommandLine.Help.Ansi.OFF)); }
Example #20
Source File: DefaultProviderTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testDefaultValueInDescriptionWithErrorProvider() { String expected2 = String.format("" + "Usage: <main class> [OPTIONS] [<paramStringFieldWithoutDefaultNorInitialValue>] [<paramStringFieldWithAnnotatedDefault>] [<paramStringFieldWithInitDefault>]%n" + " [<paramStringFieldWithoutDefaultNorInitialValue>]%n" + " Default: null%n" + " Default: null%n" + " [<paramStringFieldWithAnnotatedDefault>]%n" + " Default: Annotated default value%n" + " [<paramStringFieldWithInitDefault>]%n" + " Default: Initial default value%n" + " -a=<optionStringFieldWithoutDefaultNorInitialValue>%n" + " Default: null%n" + " -b=<optionStringFieldWithAnnotatedDefault>%n" + " Default: Annotated default value%n" + " -c=<optionStringFieldWithInitDefault>%n" + " Default: Initial default value%n" + " Default: Initial default value%n" + " -d=<string> Default: Annotated setter default value%n"); CommandLine cmd = new CommandLine(App.class); cmd.setDefaultValueProvider(new IDefaultValueProvider() { public String defaultValue(ArgSpec argSpec) throws Exception { throw new IllegalStateException("abc"); } }); assertEquals(expected2, cmd.getUsageMessage(CommandLine.Help.Ansi.OFF)); }
Example #21
Source File: ArgSplitTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testArgSpecSplitValue_MultipleQuotedValues_QuotesTrimmedIfRequested() { ParserSpec parser = new ParserSpec().trimQuotes(true); ArgSpec spec = PositionalParamSpec.builder().type(String[].class).splitRegex(",").build(); String[] actual = spec.splitValue("a,b,\"c,d,e\",f,\"xxx,yyy\"", parser, Range.valueOf("0"), 0); assertArrayEquals(new String[]{"a", "b", "c,d,e", "f", "xxx,yyy"}, actual); }
Example #22
Source File: ArgSplitTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testArgSpecSplitValue_MultipleQuotedValues() { ParserSpec parser = new ParserSpec(); ArgSpec spec = PositionalParamSpec.builder().type(String[].class).splitRegex(",").build(); String[] actual = spec.splitValue("a,b,\"c,d,e\",f,\"xxx,yyy\"", parser, Range.valueOf("0"), 0); assertArrayEquals(new String[]{"a", "b", "\"c,d,e\"", "f", "\"xxx,yyy\""}, actual); }
Example #23
Source File: ArgSplitTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testArgSpecSplitValue_SplitsQuotedValuesIfConfigured() { ParserSpec parser = new ParserSpec().splitQuotedStrings(true); ArgSpec spec = PositionalParamSpec.builder().type(String[].class).splitRegex(",").build(); String[] actual = spec.splitValue("a,b,\"c,d,e\",f", parser, Range.valueOf("0"), 0); assertArrayEquals(new String[]{"a", "b", "\"c", "d" , "e\"", "f"}, actual); }
Example #24
Source File: I18nTest.java From picocli with Apache License 2.0 | 5 votes |
private void assertArgsHaveBundle(ResourceBundle orig, List<? extends ArgSpec> args) { assertFalse("args should not be empty", args.isEmpty()); for (ArgSpec arg : args) { assertNotNull("Messages for " + arg.toString(), arg.messages()); assertSame(arg.toString(), orig, arg.messages().resourceBundle()); } }
Example #25
Source File: CommandLineTest.java From picocli with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Test public void testInterpreterApplyValueToSingleValuedField() throws Exception { Class c = Class.forName("picocli.CommandLine$Interpreter"); Class lookBehindClass = Class.forName("picocli.CommandLine$LookBehind"); Method applyValueToSingleValuedField = c.getDeclaredMethod("applyValueToSingleValuedField", ArgSpec.class, boolean.class, lookBehindClass, boolean.class, Range.class, Stack.class, Set.class, String.class); applyValueToSingleValuedField.setAccessible(true); CommandSpec spec = CommandSpec.create(); spec.parser().trimQuotes(true); CommandLine cmd = new CommandLine(spec); Object interpreter = TestUtil.interpreter(cmd); Method clear = c.getDeclaredMethod("clear"); clear.setAccessible(true); clear.invoke(interpreter); // initializes the interpreter instance PositionalParamSpec arg = PositionalParamSpec.builder().arity("1").build(); Object SEPARATE = lookBehindClass.getDeclaredField("SEPARATE").get(null); int value = (Integer) applyValueToSingleValuedField.invoke(interpreter, arg, false, SEPARATE, false, Range.valueOf("1"), new Stack<String>(), new HashSet<String>(), ""); assertEquals(0, value); }
Example #26
Source File: ReflectionConfigGenerator.java From picocli with Apache License 2.0 | 5 votes |
private void visitArgSpec(ArgSpec argSpec) throws Exception { visitGetter(argSpec.getter()); visitSetter(argSpec.setter()); visitTypeInfo(argSpec.typeInfo()); visitObjectType(argSpec.completionCandidates()); visitObjectType(argSpec.parameterConsumer()); visitObjectTypes(argSpec.converters()); }
Example #27
Source File: TomlConfigFileDefaultProvider.java From besu with Apache License 2.0 | 5 votes |
@Override public String defaultValue(final ArgSpec argSpec) { loadConfigurationFromFile(); // only options can be used in config because a name is needed for the key // so we skip default for positional params return argSpec.isOption() ? getConfigurationValue(((OptionSpec) argSpec)) : null; }
Example #28
Source File: InteractiveParameterConsumer.java From picocli with Apache License 2.0 | 5 votes |
public void consumeParameters(Stack<String> args, ArgSpec argSpec, CommandSpec commandSpec) { try { argSpec.setValue(reader.readLine(String .format("Enter %s: ", argSpec.paramLabel()), '\0')); } catch (IOException e) { throw new CommandLine.ParameterException(commandSpec.commandLine() , "Error while reading interactivly", e, argSpec, ""); } }
Example #29
Source File: AnnotatedCommandSourceGenerator.java From picocli with Apache License 2.0 | 5 votes |
private String appendCompletionCandidates(PrintWriter pw, String prefix, String newPrefix, ArgSpec argSpec) { Iterable<String> completionCandidates = argSpec.completionCandidates(); if (completionCandidates == null || isDefault(completionCandidates) || argSpec.typeInfo().isEnum()) { return prefix; } pw.print(prefix); pw.printf("completionCandidates = %s.class", extractClassName(completionCandidates)); return newPrefix; }
Example #30
Source File: YamlConfigFileDefaultProvider.java From teku with Apache License 2.0 | 5 votes |
@Override public String defaultValue(final ArgSpec argSpec) { if (result == null) { result = loadConfigurationFromFile(); checkConfigurationValidity(result == null || result.isEmpty()); checkUnknownOptions(result); } // only options can be used in config because a name is needed for the key // so we skip default for positional params return argSpec.isOption() ? getConfigurationValue(((OptionSpec) argSpec)) : null; }