@Test public void usingBuiltInCoercers() throws Exception { cli = new CLI() { { option("-c").takingArgument("CLASSNAME").ofType(Class.class); operand("file").ofType(File.class); } }; cli.parse("-c", "java.lang.String", "/path/to/file"); assertEquals(String.class, cli.get("-c")); assertEquals(new File("/path/to/file"), cli.get("file")); }
@Test public void usingPositionalArguments() throws Exception { cli = new CLI() { { operand("input").describedAs("The input file"); operand("output").describedAs("The output file"); } }; cli.parse("input", "output"); assertEquals("input", cli.get("input")); assertEquals("output", cli.get("output")); }
@Test public void specifyingADefaultValueForAnOption() throws Exception { cli = new CLI() { { option("-b").takingArgument("SIZE").ofType(int.class).defaultingTo(1024); } }; cli.parse(); assertEquals(1024, cli.get("-b")); }
@Test public void usingACustomOptionType() throws Exception { cli = new CLI() { { coerceType(BigDecimal.class).using(new BigDecimalCoercer()); option("--size VALUE").ofType(BigDecimal.class); } }; cli.parse("--size", "1000.00"); assertEquals(new BigDecimal("1000.00"), cli.get("--size")); }
@Test public void specifyingTheTypeOfAnOptionArgument() throws Exception { cli = new CLI() { { option("-b").takingArgument("SIZE").ofType(int.class); } }; cli.parse("-b", "1024"); int blockSize = cli.<Integer>get("-b"); assertEquals(1024, blockSize); }
@Test public void definingAnOptionThatExpectsAnArgument() throws Exception { cli = new CLI() { { option("-b").takingArgument("SIZE"); } }; cli.parse("-b", "1024"); assertTrue(cli.has("-b")); assertEquals("1024", cli.get("-b")); }
@Test public void specifyingTheTypeOfAPositionalArgument() throws ParsingException { cli = new CLI() { { operand("input").ofType(File.class); } }; cli.parse("/path/to/input"); File inputFile = cli.get("input"); assertEquals("/path/to/input", inputFile.getAbsolutePath()); }
@Test public void aMoreComplexExampleThatUsesAMixOfDifferentArguments() throws Exception { cli = new CLI() { { flag("-h").describedAs("Human readable format"); option("-b").alias("--block-size").takingArgument("SIZE").ofType(int.class); flag("-x"); operand("input").as("INFILE").describedAs("The input file"); operand("output", "OUTFILE", "The output file"); } }; cli.parse("-h", "--block-size", "1024", "-x", "input", "output", "extra", "more extra"); assertEquals(6, cli.options().size()); assertTrue(cli.has("-h")); assertEquals(1024, cli.get("--block-size")); assertTrue(cli.has("-x")); assertEquals("input", cli.get("input")); assertEquals("output", cli.get("output")); assertEquals(asList("extra", "more extra"), cli.others()); }
@Test public void specifyingAnOptionInLiteralForm() throws Exception { cli = new CLI() { { option("-h", "--host HOSTNAME", "Hostname to bind to"); } }; cli.parse("--host", "0.0.0.0"); assertTrue(cli.has("-h")); assertTrue(cli.has("--host")); assertEquals("0.0.0.0", cli.get("-h")); }