picocli.CommandLine.Option Java Examples
The following examples show how to use
picocli.CommandLine.Option.
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: AtFileTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testAtFileExpandedMixedWithOtherParams() { class App { @Option(names = "-x") private boolean xxx; @Option(names = "-f") private String[] fff; @Option(names = "-v") private boolean verbose; @Parameters private List<String> files; } File file = findFile("/argfile1.txt"); App app = CommandLine.populateCommand(new App(), "-f", "fVal1", "@" + file.getAbsolutePath(), "-x", "-f", "fVal2"); assertTrue(app.verbose); assertEquals(Arrays.asList("1111", "2222", ";3333"), app.files); assertTrue(app.xxx); assertArrayEquals(new String[]{"fVal1", "fVal2"}, app.fff); }
Example #2
Source File: NegatableOptionTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testAllowBooleanOptionsToGetValueFromFallback() { @Command(defaultValueProvider = Issue754DefaultProvider.class) class App { @Option(names = "-x", fallbackValue = "false", defaultValue = "true") boolean x; @Option(names = "-y", fallbackValue = "true", defaultValue = "false") boolean y; @Option(names = "-z", fallbackValue = "false") boolean z; } App app = new App(); assertFalse(app.x); assertFalse(app.y); assertFalse(app.z); app.x = true; app.z = true; new CommandLine(app).parseArgs("-x", "-y", "-z"); assertFalse(app.x); assertTrue(app.y); assertFalse(app.z); }
Example #3
Source File: ArgGroupTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testValidationGroups2Violations2BothExclusiveMultiplicity0_1_ActualTwo() { class Group1 { @Option(names = "-a", required = true) boolean a; @Option(names = "-b", required = true) boolean b; } class Group2 { @Option(names = "-x", required = true) boolean x; @Option(names = "-y", required = true) boolean y; } class App { @ArgGroup(exclusive = true, multiplicity = "0..1") Group1 g1; @ArgGroup(exclusive = true, multiplicity = "0..1") Group2 g2; } try { new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-x", "-y", "-a", "-b"); fail("Expected exception"); } catch (MutuallyExclusiveArgsException ex) { assertEquals("Error: -x, -y are mutually exclusive (specify only one)", ex.getMessage()); } }
Example #4
Source File: ArgSplitTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testQuotedMapKeysTrimQuotesWithSplit() { class App { @Option(names = "-e", split = ",") Map<String, String> map = new HashMap<String, String>(); } App app = new App(); new CommandLine(app).setTrimQuotes(true).parseArgs("-e", "\"\\\"a=b=c\\\"=foo\",\"\\\"d=e=f\\\"=bar\""); assertTrue(app.map.containsKey("a=b=c")); assertTrue(app.map.containsKey("d=e=f")); assertEquals("foo", app.map.get("a=b=c")); assertEquals("bar", app.map.get("d=e=f")); new CommandLine(app).setTrimQuotes(true).parseArgs("-e", "\"\\\"a=b=c\\\"=x=y=z\",\"\\\"d=e=f\\\"=x2=y2\""); assertTrue(app.map.keySet().toString(), app.map.containsKey("a=b=c")); assertTrue(app.map.keySet().toString(), app.map.containsKey("d=e=f")); assertEquals("x=y=z", app.map.get("a=b=c")); assertEquals("x2=y2", app.map.get("d=e=f")); }
Example #5
Source File: ArgGroupTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testValidationExclusiveMultiplicity1_ActualZero() { class All { @Option(names = "-a", required = true) boolean a; @Option(names = "-b", required = true) boolean b; } class App { @ArgGroup(exclusive = true, multiplicity = "1") All all; } try { new CommandLine(new App(), new InnerClassFactory(this)).parseArgs(); fail("Expected exception"); } catch (MissingParameterException ex) { assertEquals("Error: Missing required argument (specify one of these): (-a | -b)", ex.getMessage()); } }
Example #6
Source File: LoggingMixin.java From picocli with Apache License 2.0 | 6 votes |
/** * Sets the specified verbosity on the LoggingMixin of the top-level command. * @param verbosity the new verbosity value */ @Option(names = {"-v", "--verbose"}, description = { "Specify multiple -v options to increase verbosity.", "For example, `-v -v -v` or `-vvv`"} ) public void setVerbose(boolean[] verbosity) { // Each subcommand that mixes in the LoggingMixin has its own instance of this class, // so there may be many LoggingMixin instances. // We want to store the verbosity state in a single, central place, so // we find the top-level command (which _must_ implement LoggingMixin.IOwner), // and store the verbosity level on that top-level command's LoggingMixin. // // In the main method, `LoggingMixin::executionStrategy` should be set as the execution strategy: // that will take the verbosity level that we stored in the top-level command's LoggingMixin // to configure Log4j2 before executing the command that the user specified. IOwner owner = spec.root().commandLine().getCommand(); owner.getLoggingMixin().verbosity = verbosity; }
Example #7
Source File: AtFileTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testAtFileExpandedRelative() { 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()); } App app = CommandLine.populateCommand(new App(), "@" + relative); assertTrue(app.verbose); assertEquals(Arrays.asList("1111", "2222", ";3333"), app.files); }
Example #8
Source File: ArgGroupTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testUsageHelpRequiredExclusiveGroup() { class Excl { @Option(names = "-x", required = true) boolean x; @Option(names = "-y", required = true) boolean y; } class App { @ArgGroup(exclusive = true, multiplicity = "1") Excl excl; } String expected = String.format("" + "Usage: <main class> (-x | -y)%n" + " -x%n" + " -y%n"); String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF); assertEquals(expected, actual); }
Example #9
Source File: AbstractCommandSpecProcessor.java From picocli with Apache License 2.0 | 6 votes |
private boolean isSubcommand(ExecutableElement method, RoundEnvironment roundEnv) { Element typeElement = method.getEnclosingElement(); if (typeElement.getAnnotation(Command.class) != null && typeElement.getAnnotation(Command.class).addMethodSubcommands()) { return true; } if (typeElement.getAnnotation(Command.class) == null) { Set<Element> elements = new HashSet<Element>(typeElement.getEnclosedElements()); // The class is a Command if it has any fields or methods annotated with the below: return roundEnv.getElementsAnnotatedWith(Option.class).removeAll(elements) || roundEnv.getElementsAnnotatedWith(Parameters.class).removeAll(elements) || roundEnv.getElementsAnnotatedWith(Mixin.class).removeAll(elements) || roundEnv.getElementsAnnotatedWith(ArgGroup.class).removeAll(elements) || roundEnv.getElementsAnnotatedWith(Unmatched.class).removeAll(elements) || roundEnv.getElementsAnnotatedWith(Spec.class).removeAll(elements); } return false; }
Example #10
Source File: ArgGroupTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testUsageHelpNonValidatingGroupDoesNotImpactSynopsis() { class All { @Option(names = "-x") boolean x; @Option(names = "-y") boolean y; } class App { @ArgGroup(validate = false) All all; } String expected = String.format("" + "Usage: <main class> [-xy]%n" + " -x%n" + " -y%n"); String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF); assertEquals(expected, actual); }
Example #11
Source File: AtFileTest.java From picocli with Apache License 2.0 | 6 votes |
@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 #12
Source File: I18nTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testIssue670NoScrambledCharactersOnJava9() { try { Class.forName("java.lang.Runtime$Version"); // introduced in Java 9 } catch (ClassNotFoundException e) { return; } @Command(name = "tests", aliases = {"t"}, resourceBundle = "picocli.i18n.SG_cli") class App { @Option(names = {"-a", "--auth"}, descriptionKey = "auth.desc") boolean auth; @Option(names = {"-u", "--upload"}, descriptionKey = "upload.desc") String upload; } Locale original = Locale.getDefault(); Locale.setDefault(Locale.FRENCH); String expected = String.format(Locale.FRENCH, "" + "Usage: tests [-a] [-u=<upload>]%n" + " -a, --auth V\u00e9rifie si l'utilisateur est connecte%n" + " -u, --upload=<upload> Tester le t\u00e9l\u00e9versement de fichiers.%n" + " Attend un chemin complet de fichier.%n"); try { assertEquals(new CommandLine(new App()).getUsageMessage(), expected, new CommandLine(new App()).getUsageMessage()); } finally { Locale.setDefault(original); } }
Example #13
Source File: UnmatchedOptionTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testMultiValueVarArgPositionalDoesNotConsumeActualOption() { class App { @Option(names = "-x") int x; @Parameters(arity = "*") String[] y; } expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "-x"); expect(new App(), "option '-x' (<x>) should be specified only once", OverwrittenOptionException.class, "-x", "3", "-x", "4"); expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "4", "-x"); App app = new App(); new CommandLine(app).parseArgs("-x", "3", "4"); assertEquals(3, app.x); assertArrayEquals(new String[]{"4"}, app.y); }
Example #14
Source File: InterpolatedModelTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testIssue723_withStandardHelpOptions() { @Command(mixinStandardHelpOptions = true, showDefaultValues = true) class Issue723 { @Option(names="--mypath", defaultValue = "${sys:user.home}", description = "Path. Default=${DEFAULT-VALUE}.") private String path; } String expected = String.format("" + "Usage: <main class> [-hV] [--mypath=<path>]%n" + " -h, --help Show this help message and exit.%n" + " --mypath=<path> Path. Default=%1$s.%n" + " Default: %1$s%n" + " -V, --version Print version information and exit.%n", System.getProperty("user.home")); String actual = new CommandLine(new Issue723()).getUsageMessage(CommandLine.Help.Ansi.OFF); assertEquals(expected, actual); }
Example #15
Source File: AtFileTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testAtFileExpandedWithNonDefaultCommentChar() { class App { @Option(names = "-x") private boolean xxx; @Option(names = "-f") private String[] fff; @Option(names = "-v") private boolean verbose; @Parameters private List<String> files; } File file = findFile("/argfile1.txt"); App app = new App(); CommandLine cmd = new CommandLine(app); cmd.setAtFileCommentChar(';'); cmd.parseArgs("-f", "fVal1", "@" + file.getAbsolutePath(), "-x", "-f", "fVal2"); assertTrue(app.verbose); assertEquals(Arrays.asList("#", "first", "comment", "1111", "2222", "#another", "comment"), app.files); assertTrue(app.xxx); assertArrayEquals(new String[]{"fVal1", "fVal2"}, app.fff); }
Example #16
Source File: UnmatchedOptionTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testSingleValuePositionalCanBeConfiguredToConsumeUnknownOption() { class App { @Option(names = "-x") int x; @Parameters String y; } App app = new App(); new CommandLine(app).setUnmatchedOptionsArePositionalParams(true).parseArgs("-x", "3", "-z"); assertEquals(3, app.x); assertEquals("-z", app.y); CommandLine cmd = new CommandLine(new App()).setUnmatchedOptionsArePositionalParams(true); expect(cmd, "Unmatched argument at index 3: '4'", UnmatchedArgumentException.class, "-x", "3", "-z", "4"); }
Example #17
Source File: DefaultProviderTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testIssue962DefaultNotUsedIfArgumentSpecifiedOnCommandLine() { class App { List<Integer> specified = new ArrayList<Integer>(); @Option(names = "--port", defaultValue = "${sys:TEST_PORT_962}", required = true) void setPort(Integer port) { specified.add(port); } @Option(names = "--field", defaultValue = "${sys:TEST_A_962}", required = true) Integer a; } System.setProperty("TEST_PORT_962", "xxx"); System.setProperty("TEST_A_962", "xxx"); App app1 = CommandLine.populateCommand(new App(), "--port=123", "--field=987"); assertEquals((Integer) 987, app1.a); assertEquals(Arrays.asList(123), app1.specified); }
Example #18
Source File: ModelCommandSpecTest.java From picocli with Apache License 2.0 | 6 votes |
@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 #19
Source File: UnmatchedOptionTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testMultiValuePositionalDoesNotConsumeActualOption() { class App { @Option(names = "-x") int x; @Parameters String[] y; } expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "-x"); expect(new App(), "option '-x' (<x>) should be specified only once", OverwrittenOptionException.class, "-x", "3", "-x", "4"); expect(new App(), "Missing required parameter for option '-x' (<x>)", MissingParameterException.class, "-x", "3", "4", "-x"); App app = new App(); new CommandLine(app).parseArgs("-x", "3", "4"); assertEquals(3, app.x); assertArrayEquals(new String[]{"4"}, app.y); }
Example #20
Source File: ArgGroupTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testValidationDependentMultiplicity0_1_Partial() { class All { @Option(names = "-a", required = true) boolean a; @Option(names = "-b", required = true) boolean b; @Option(names = "-c", required = true) boolean c; } class App { @ArgGroup(exclusive = false) All all; } try { new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b"); fail("Expected exception"); } catch (MissingParameterException ex) { assertEquals("Error: Missing required argument(s): -c", ex.getMessage()); } }
Example #21
Source File: ArgSplitTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testSplitInOptionCollection() { class Args { @Option(names = "-a", split = ",") List<String> values; } Args args = CommandLine.populateCommand(new Args(), "-a=a,b,c"); assertEquals(Arrays.asList("a", "b", "c"), args.values); args = CommandLine.populateCommand(new Args(), "-a=a,b,c", "-a", "B", "-a=C"); assertEquals(Arrays.asList("a", "b", "c", "B", "C"), args.values); args = CommandLine.populateCommand(new Args(), "-a", "a,b,c", "-a", "B", "-a", "C"); assertEquals(Arrays.asList("a", "b", "c", "B", "C"), args.values); args = CommandLine.populateCommand(new Args(), "-a=a,b,c", "-a", "B", "-a", "C", "-a", "D,E,F"); assertEquals(Arrays.asList("a", "b", "c", "B", "C", "D", "E", "F"), args.values); try { CommandLine.populateCommand(new Args(), "-a=a,b,c", "B", "C"); fail("Expected UnmatchedArgumentException"); } catch (UnmatchedArgumentException ok) { assertEquals("Unmatched arguments from index 1: 'B', 'C'", ok.getMessage()); } }
Example #22
Source File: ArgSplitTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void test379WithTrimQuotes() { String[] args = { "-p", "AppOptions=\"-Dspring.profiles.active=foo,bar -Dspring.mail.host=smtp.mailtrap.io\",OtherOptions=\"\"" }; class App { @Option(names = {"-p", "--parameter"}, split = ",") Map<String, String> parameters; } App app = new App(); new CommandLine(app).setTrimQuotes(true).parseArgs(args); assertEquals(2, app.parameters.size()); assertEquals("-Dspring.profiles.active=foo,bar -Dspring.mail.host=smtp.mailtrap.io", app.parameters.get("AppOptions")); assertEquals("", app.parameters.get("OtherOptions")); }
Example #23
Source File: InheritedOptionTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testGlobalOptionDisallowedIfSubcommandAlreadyHasGlobalOptionWithSameName() { Top top = new Top(); CommandLine cmd = new CommandLine(top); class Other { @Option(names = "--verbose", scope = INHERIT) boolean verbose; } Other other = new Other(); try { cmd.addSubcommand("other", other); fail("Expected exception"); } catch (DuplicateOptionAnnotationsException ex) { String msg = String.format("Option name '--verbose' is used by both field boolean %s.verbose and field boolean %s.verbose", top.getClass().getName(), other.getClass().getName()); assertEquals(msg, ex.getMessage()); } //cmd.parseArgs("other", "--verbose"); //assertTrue(top.verbose); //assertFalse(other.verbose); }
Example #24
Source File: VersionProviderTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testPrintVersionHelpPrintWriter() { @Command(version = "abc 1.2.3 myversion") class App { @Option(names = "-V", versionHelp = true) boolean versionRequested; } StringWriter sw = new StringWriter(); new CommandLine(new App()).printVersionHelp(new PrintWriter(sw)); assertEquals(String.format("abc 1.2.3 myversion%n"), sw.toString()); }
Example #25
Source File: SplitSynopsisLabelTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testOptionWithoutSplit() { @Command(name = "WithoutSplit") class WithoutSplit { @Option(names = "v", splitSynopsisLabel = "|", description = "xxx yyy zzz") String args[] = {}; } String expected = String.format("" + "Usage: WithoutSplit [v=<args>]...%n" + " v=<args> xxx yyy zzz%n"); String actual = new CommandLine(new WithoutSplit()).getUsageMessage(OFF); assertEquals(expected, actual); }
Example #26
Source File: InteractiveArgTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testInteractiveOptionAsListOfCharArraysArity_0_1_AvoidsConsumingOption() throws IOException { class App { @Option(names = "-x", arity = "0..1", interactive = true) List<char[]> x; @Option(names = "-z") int z; @Parameters() String[] remainder; } PrintStream out = System.out; InputStream in = System.in; try { System.setOut(new PrintStream(new ByteArrayOutputStream())); System.setIn(inputStream("123")); App app = new App(); CommandLine cmd = new CommandLine(app); cmd.parseArgs("-x", "-z", "456", "abc"); assertEquals(1, app.x.size()); assertArrayEquals("123".toCharArray(), app.x.get(0)); assertEquals(456, app.z); assertArrayEquals(new String[]{"abc"}, app.remainder); } finally { System.setOut(out); System.setIn(in); } }
Example #27
Source File: ArgGroupTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testValidationDependentSomeOptionalMultiplicity0_1_All() { class All { @Option(names = "-a", required = true) boolean a; @Option(names = "-b", required = false) boolean b; @Option(names = "-c", required = true) boolean c; } class App { @ArgGroup(exclusive = false) All all; } new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b", "-c"); }
Example #28
Source File: InteractiveArgTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testInteractiveOptionAsListOfIntegers() throws IOException { class App { @Option(names = "-x", description = {"Pwd", "line2"}, interactive = true) List<Integer> x; @Option(names = "-z") int z; } PrintStream out = System.out; InputStream in = System.in; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos)); System.setIn(inputStream("123")); App app = new App(); CommandLine cmd = new CommandLine(app); cmd.parseArgs("-x", "-x"); assertEquals("Enter value for -x (Pwd): Enter value for -x (Pwd): ", baos.toString()); assertEquals(Arrays.asList(123, 123), app.x); assertEquals(0, app.z); cmd.parseArgs("-z", "678"); assertNull(app.x); assertEquals(678, app.z); } finally { System.setOut(out); System.setIn(in); } }
Example #29
Source File: ArgSplitTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testSplitIgnoredInOptionSingleValueFieldIfSystemPropertySet() { class Args { @Option(names = "-a", split = ",") String value; } System.setProperty("picocli.ignore.invalid.split", ""); Args args = CommandLine.populateCommand(new Args(), "-a=a,b,c"); assertEquals("a,b,c", args.value); }
Example #30
Source File: HarvesterOptions.java From cassandra-exporter with Apache License 2.0 | 5 votes |
@Option(names = "--exclude-system-tables", description = "Exclude system table/keyspace metrics.") public void setExcludeSystemTables(final boolean excludeSystemTables) { if (!excludeSystemTables) { throw new IllegalStateException(); } excludedKeyspaces.addAll(CASSANDRA_SYSTEM_KEYSPACES); }