picocli.CommandLine.Model.CommandSpec Java Examples
The following examples show how to use
picocli.CommandLine.Model.CommandSpec.
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: ExecuteLegacyTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testExecutionExceptionIfRunnableThrowsExecutionException() { @Command class App implements Runnable { @Spec CommandSpec spec; public void run() { throw new ExecutionException(spec.commandLine(), "abc"); } } try { CommandLine.run(new App()); fail("Expected exception"); } catch (ExecutionException ex) { assertEquals("abc", ex.getMessage()); } }
Example #2
Source File: VersionProviderTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testInitVersionProvider() { CommandLine.IVersionProvider versionProvider1 = new CommandLine.IVersionProvider() { public String[] getVersion() { return new String[0]; } }; CommandLine.IVersionProvider versionProvider2 = new CommandLine.IVersionProvider() { public String[] getVersion() { return new String[0]; } }; CommandSpec spec = CommandSpec.wrapWithoutInspection(null); spec.versionProvider(versionProvider1); CommandSpec mixin = CommandSpec.wrapWithoutInspection(null); mixin.versionProvider(versionProvider2); spec.addMixin("helper", mixin); assertSame(versionProvider1, spec.versionProvider()); }
Example #3
Source File: ModelCommandSpecTest.java From picocli with Apache License 2.0 | 6 votes |
@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 #4
Source File: CommandSpecFactory.java From milkman with MIT License | 6 votes |
CommandSpec getSpecFor(TerminalCommand cmd) { var cmdSpec = CommandSpec.wrapWithoutInspection(cmd); cmdSpec.name(cmd.getName()) .aliases(cmd.getAlias()) .usageMessage(new UsageMessageSpec() .description(cmd.getDescription())); int idx = 0; for (Parameter parameter : cmd.getParameters()) { addPositionalParameter(cmdSpec, parameter, idx); idx++; } for(Option option : cmd.getOptions()) { addBooleanOption(cmdSpec, option); } return cmdSpec; }
Example #5
Source File: AbstractCompositeGeneratorProcessor.java From picocli with Apache License 2.0 | 6 votes |
@Override protected boolean handleCommands(Map<Element, CommandSpec> commands, Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (!roundEnv.processingOver()) { allCommands.putAll(commands); return false; } try { for (IGenerator generator : generators) { generator.generate(allCommands); } } catch (Exception e) { // Generators are supposed to do their own error handling, but let's be paranoid. // We don't allow exceptions of any kind to propagate to the compiler fatalError(ProcessorUtil.stacktrace(e)); } return false; }
Example #6
Source File: ModelCommandSpecTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testPositionalClearCustomSetterBeforeParse() { 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.add(PositionalParamSpec.builder().type(String.class).setter(setter).build()); CommandLine cl = new CommandLine(cmd); assertTrue(values.isEmpty()); cl.parseArgs("1"); assertEquals(2, values.size()); assertEquals(null, values.get(0)); assertEquals("1", values.get(1)); values.clear(); cl.parseArgs("2"); assertEquals(2, values.size()); assertEquals(null, values.get(0)); assertEquals("2", values.get(1)); }
Example #7
Source File: ModelMethodBindingTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testSetFailsIfObjectNotSet_ForSetterMethod() throws Exception { Method setX = ModelMethodBindingBean.class.getDeclaredMethod("setX", int.class); setX.setAccessible(true); CommandSpec spec = CommandSpec.create(); MethodBinding binding = new MethodBinding(new ObjectScope(null), setX, spec); try { binding.set(41); fail("Expect exception"); } catch (Exception ex) { ParameterException pex = (ParameterException) ex; assertSame(spec, pex.getCommandLine().getCommandSpec()); assertThat(pex.getCause().getClass().toString(), pex.getCause() instanceof NullPointerException); } }
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: ModelUsageMessageSpecTest.java From picocli with Apache License 2.0 | 6 votes |
@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 #10
Source File: CommandMethodTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testTypedMemberInitializeInitialValue() throws Exception { Constructor<TypedMember> constructor = TypedMember.class.getDeclaredConstructor(Method.class, IScope.class, CommandSpec.class); constructor.setAccessible(true); Method setter = TypedMemberObj.class.getDeclaredMethod("setter", String.class); TypedMember typedMember = constructor.newInstance(setter, new ObjectScope(new TypedMemberObj()), CommandSpec.create()); Method initializeInitialValue = TypedMember.class.getDeclaredMethod("initializeInitialValue", Object.class); initializeInitialValue.setAccessible(true); try { initializeInitialValue.invoke(typedMember, "boom"); } catch (InvocationTargetException ite) { InitializationException ex = (InitializationException) ite.getCause(); assertTrue(ex.getMessage().startsWith("Could not set initial value for boom")); } }
Example #11
Source File: ModelCommandSpecTest.java From picocli with Apache License 2.0 | 6 votes |
@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 #12
Source File: ExecuteTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testCommandSpecExitCodesFromAnnotations() { @Command(exitCodeOnSuccess = 1 , exitCodeOnUsageHelp = 2 , exitCodeOnVersionHelp = 3 , exitCodeOnInvalidInput = 4 , exitCodeOnExecutionException = 5) class Annotated{} CommandSpec spec = CommandSpec.forAnnotatedObject(new Annotated()); assertEquals(1, spec.exitCodeOnSuccess()); assertEquals(2, spec.exitCodeOnUsageHelp()); assertEquals(3, spec.exitCodeOnVersionHelp()); assertEquals(4, spec.exitCodeOnInvalidInput()); assertEquals(5, spec.exitCodeOnExecutionException()); }
Example #13
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 #14
Source File: ExecuteTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testExitCodeListProgrammaticCannotOverwriteResourceBundleValues() { @Command(resourceBundle = "picocli.exitcodes") class App {} Map<String, String> bundleValues = keyValuesMap( " 0:Normal termination (notice leading space)", "64:Multiline!%nInvalid input", "70:Very long line: aaaaa bbbbbbbb ccccc dddddddd eeeeeee fffffffff ggggg hhhh iiii jjjjjjj kkkk lllll mmmmmmmm nn ooooo ppppp qqqqq" ); CommandLine cmd = new CommandLine(new App()); CommandSpec spec = cmd.getCommandSpec(); assertEquals(bundleValues, spec.usageMessage().exitCodeList()); Map<String, String> map = keyValuesMap( " 0:AAA", " 1:BBB", "22:CCC"); spec.usageMessage().exitCodeList(map); // ignored assertEquals(bundleValues, spec.usageMessage().exitCodeList()); }
Example #15
Source File: AutoComplete.java From picocli with Apache License 2.0 | 5 votes |
private static void addCandidatesForArgsFollowing(Object obj, List<CharSequence> candidates) { if (obj == null) { return; } if (obj instanceof CommandSpec) { addCandidatesForArgsFollowing((CommandSpec) obj, candidates); } else if (obj instanceof OptionSpec) { addCandidatesForArgsFollowing((OptionSpec) obj, candidates); } else if (obj instanceof PositionalParamSpec) { addCandidatesForArgsFollowing((PositionalParamSpec) obj, candidates); } }
Example #16
Source File: ModelCommandSpecTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testPositionalParamSpec_DefaultValue_list_replacedByCommandLineValue() { CommandSpec cmd = CommandSpec.create().add(PositionalParamSpec .builder().defaultValue("1,2,3").splitRegex(",").type(List.class).auxiliaryTypes(Integer.class).build()); ParseResult parseResult = new CommandLine(cmd).parseArgs("4,5,6"); assertEquals(Arrays.asList(4, 5, 6), parseResult.matchedPositionalValue(0, Collections.emptyList())); }
Example #17
Source File: AbstractCommandSpecProcessor.java From picocli with Apache License 2.0 | 5 votes |
private static CommandSpec getOrCreateCommandSpecForArg(Element argElement, Map<Element, CommandSpec> commands) { Element key = argElement.getEnclosingElement(); CommandSpec commandSpec = commands.get(key); if (commandSpec == null) { logger.fine("Element " + argElement + " is enclosed by " + key + " which does not have a @Command annotation"); commandSpec = CommandSpec.forAnnotatedObjectLenient(key); commandSpec.interpolateVariables(false); commands.put(key, commandSpec); } return commandSpec; }
Example #18
Source File: InterpolatorTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void interpolateCommandName() { CommandSpec hierarchy = createTestSpec(); CommandSpec spec = hierarchy.subcommands().get("sub").getSubcommands().get("subsub").getCommandSpec(); Interpolator interpolator = new Interpolator(spec); String original = "This is a description for ${COMMAND-NAME}, whose fqcn is ${COMMAND-FULL-NAME}. It's parent is ${PARENT-COMMAND-NAME}, also known as ${PARENT-COMMAND-FULL-NAME}. It's root is ${ROOT-COMMAND-NAME}."; String expected = "This is a description for subsub, whose fqcn is top sub subsub. It's parent is sub, also known as top sub. It's root is top."; assertEquals(expected, interpolator.interpolate(original)); }
Example #19
Source File: ModelCommandSpecTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testMultiValuePositionalParamWithArray() { CommandSpec spec = CommandSpec.create(); PositionalParamSpec positional = PositionalParamSpec.builder().index("0").arity("3").type(int[].class).build(); assertTrue(positional.isMultiValue()); spec.addPositional(positional); CommandLine commandLine = new CommandLine(spec); commandLine.parseArgs("1", "2", "3"); assertArrayEquals(new int[] {1, 2, 3}, (int[]) spec.positionalParameters().get(0).getValue()); }
Example #20
Source File: AbstractCommandSpecProcessor.java From picocli with Apache License 2.0 | 5 votes |
private void registerCommandType(CommandSpec result, TypeElement typeElement) { List<CommandSpec> forSubclass = commandTypes.get(typeElement.asType()); if (forSubclass == null) { forSubclass = new ArrayList<CommandSpec>(); commandTypes.put(typeElement.asType(), forSubclass); } forSubclass.add(result); }
Example #21
Source File: MixeeTest.java From picocli with Apache License 2.0 | 5 votes |
private static String qualifiedName(CommandSpec spec) { if (spec.userObject() instanceof TypeElement) { TypeElement type = (TypeElement) spec.userObject(); return type.getQualifiedName().toString(); } if (spec.userObject() instanceof ExecutableElement) { ExecutableElement method = (ExecutableElement) spec.userObject(); return method.getEnclosingElement().getSimpleName() + "." + method.getSimpleName().toString(); } return null; }
Example #22
Source File: CommandSpecYamlPrinter.java From picocli with Apache License 2.0 | 5 votes |
private void printMixinList(Map<String, CommandSpec> mixins, PrintWriter pw, String indent) { pw.printf("%sMixins:", indent); pw.println(mixins.isEmpty() ? " []" : ""); for (Map.Entry<String, CommandSpec> entry : mixins.entrySet()) { printCommandSpec(entry.getValue(), indent + "# " + entry.getKey(), pw, indent + "- ", indent + " "); } }
Example #23
Source File: InheritedOptionTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testProgrammaticAddOptionAfterSub() { OptionSpec optA = OptionSpec.builder("-a").scopeType(INHERIT).build(); CommandSpec spec = CommandSpec.create(); CommandSpec sub = CommandSpec.create(); spec.addSubcommand("sub", sub); spec.add(optA); assertFalse(optA.inherited()); assertNotNull(spec.findOption("-a")); assertNotNull(sub.findOption("-a")); assertFalse(spec.findOption("-a").inherited()); assertTrue(sub.findOption("-a").inherited()); }
Example #24
Source File: AnnotatedCommandSourceGeneratorTest.java From picocli with Apache License 2.0 | 5 votes |
@Ignore @Test public void generate() { CommandSpec spec = CommandSpec.forAnnotatedObject(Example.class); String generated = new AnnotatedCommandSourceGenerator(spec).generate(); //System.out.println(generated); String expected = Resources.slurp("/picocli/codegen/aot/graalvm/Example.txt"); assertEquals(expected, generated); }
Example #25
Source File: InterpolatorTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void interpolateSystemPropertyWithMultipleLookupsInDefaultFoundFirst() { CommandSpec hierarchy = createTestSpec(); Interpolator interpolator = new Interpolator(hierarchy); String original = "abc ${sys:key:-${sys:blah} and ${sys:other:-${env:__undefined__picocli:-fixedvalue}}} dev."; String expected = "abc xxx and fixedvalue dev."; System.setProperty("blah", "xxx"); assertEquals(expected, interpolator.interpolate(original)); System.clearProperty("blah"); }
Example #26
Source File: InterpolatorTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void issue676interpolateReturnsNullIfNotFound() { CommandSpec hierarchy = createTestSpec(); Interpolator interpolator = new Interpolator(hierarchy); String original = "${sys:notfound}"; assertEquals(null, interpolator.interpolate(original)); }
Example #27
Source File: InterpolatorTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void interpolateSystemPropertyWithMultipleLookupsInDefaultFoundSecond() { CommandSpec hierarchy = createTestSpec(); Interpolator interpolator = new Interpolator(hierarchy); String original = "abc ${sys:key:-${sys:blah} and ${sys:other:-${env:__undefined__picocli:-fixedvalue}}} dev."; String expected = "abc null and yyy dev."; System.setProperty("other", "yyy"); assertEquals(expected, interpolator.interpolate(original)); System.clearProperty("other"); }
Example #28
Source File: CommandLineTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testUnmatchedExceptionIsUnknownOption() { CommandLine cmd = new CommandLine(CommandSpec.create()); assertFalse("unmatch list is null", new UnmatchedArgumentException(cmd, "").isUnknownOption()); assertFalse("unmatch list is empty", new UnmatchedArgumentException(cmd, new ArrayList<String>()).isUnknownOption()); List<String> likeAnOption = Arrays.asList("-x"); assertTrue("first unmatched resembles option", new UnmatchedArgumentException(cmd, likeAnOption).isUnknownOption()); List<String> unlikeOption = Arrays.asList("xxx"); assertFalse("first unmatched doesn't resembles option", new UnmatchedArgumentException(cmd, unlikeOption).isUnknownOption()); }
Example #29
Source File: AnnotatedCommandSourceGenerator.java From picocli with Apache License 2.0 | 5 votes |
private void printCommandAnnotation(PrintWriter pw, CommandSpec spec, String indent) { pw.printf("%s@%s", indent, importer.getImportedName(Command.class.getCanonicalName())); indent = String.format(",%n%s ", indent); String sep = "("; sep = append(pw, sep, indent, "name = \"%s\"", spec.name(), "<main class>"); sep = appendStringArray(pw, sep, indent, "aliases = %s", spec.aliases(), EMPTY_ARRAY); sep = append(pw, sep, indent, "mixinStandardHelpOptions = %s", spec.mixinStandardHelpOptions(), false); sep = append(pw, sep, indent, "headerHeading = \"%s\"", spec.usageMessage().headerHeading(), ""); sep = appendStringArray(pw, sep, indent, "header = %s", spec.usageMessage().header(), EMPTY_ARRAY); sep = append(pw, sep, indent, "descriptionHeading = \"%s\"", spec.usageMessage().descriptionHeading(), ""); sep = appendStringArray(pw, sep, indent, "description = %s", spec.usageMessage().description(), EMPTY_ARRAY); sep = append(pw, sep, indent, "synopsisHeading = \"%s\"", spec.usageMessage().synopsisHeading(), "Usage: "); sep = append(pw, sep, indent, "abbreviateSynopsis = %s", spec.usageMessage().abbreviateSynopsis(), false); sep = appendStringArray(pw, sep, indent, "customSynopsis = %s", spec.usageMessage().customSynopsis(), EMPTY_ARRAY); sep = append(pw, sep, indent, "optionListHeading = \"%s\"", spec.usageMessage().optionListHeading(), ""); sep = append(pw, sep, indent, "parameterListHeading = \"%s\"", spec.usageMessage().parameterListHeading(), ""); sep = append(pw, sep, indent, "commandListHeading = \"%s\"", spec.usageMessage().commandListHeading(), "Commands:%n"); sep = append(pw, sep, indent, "footerHeading = \"%s\"", spec.usageMessage().footerHeading(), ""); sep = appendStringArray(pw, sep, indent, "footer = %s", spec.usageMessage().footer(), EMPTY_ARRAY); sep = append(pw, sep, indent, "requiredOptionMarker = \'%s\'", spec.usageMessage().requiredOptionMarker(), ' '); sep = append(pw, sep, indent, "addMethodSubcommands = %s", spec.isAddMethodSubcommands(), !isCommandMethod(spec)); sep = appendSubcommandClasses(pw, sep, indent, spec.subcommands()); sep = appendStringArray(pw, sep, indent, "version = %s", spec.version(), EMPTY_ARRAY); sep = appendClassName(pw, sep, indent, "versionProvider = %s", spec.versionProvider()); sep = append(pw, sep, indent, "showDefaultValues = %s", spec.usageMessage().showDefaultValues(), false); sep = appendClassName(pw, sep, indent, "defaultValueProvider = %s", spec.defaultValueProvider()); sep = append(pw, sep, indent, "resourceBundle = \"%s\"", spec.resourceBundleBaseName(), "null"); sep = append(pw, sep, indent, "sortOptions = %s", spec.usageMessage().sortOptions(), true); sep = append(pw, sep, indent, "hidden = %s", spec.usageMessage().hidden(), false); sep = append(pw, sep, indent, "helpCommand = %s", spec.helpCommand(), false); sep = append(pw, sep, indent, "separator = \"%s\"", spec.parser().separator(), "="); sep = append(pw, sep, indent, "usageHelpWidth = %s", spec.usageMessage().width(), 80); if (!"(".equals(sep)) { pw.print(")"); } }
Example #30
Source File: AnnotatedCommandSourceGenerator.java From picocli with Apache License 2.0 | 5 votes |
private static boolean isMixedIn(OptionSpec option, CommandSpec spec) { for (CommandSpec mixin : spec.mixins().values()) { if (mixin.findOption(option.longestName()) != null) { return true; } } return false; }