diff --git a/docs/index.adoc b/docs/index.adoc index 5f21aa83c..a91d8b474 100644 --- a/docs/index.adoc +++ b/docs/index.adoc @@ -3033,7 +3033,7 @@ The <> of options in an argument group are applie Picocli will not initialize the `@ArgGroup`-annotated field (and so no default values are applied) if none of the group options is specified on the command line. -==== Default Values in Group Usage Help +==== Showing Default Values in Group Usage Help When options are used in argument groups, they can only define default values via the `@Option(defaultValue = "...")` annotation (not in the field declaration). @@ -3138,6 +3138,106 @@ usage help shows the wrong default value ---- ==== +==== Using Default Values in Argument Groups +For picocli, there are two recommendations for successfully employing default values. First, using default values requires setting the default value within the annotation and declaratively within your code. The second is deciding how to instantiate your objects. + +[source,role="primary"] +---- +@Option(names= {"-x"}, defaultValue = "X") String X = "X"; +---- +Matching the annotation and declaration ensures that picocli sets the default values regardless of the user supplies the arguments. + +Next, identify your preferred default behavior. For `+@ArgGroup+`'s there are two distinct ways of instantiating an object. + +The first is to instantiate the object declaratively. This behavior is best when you desire no ambiguity in whether or not an `+@ArgGroup+` is instantiated. + +.Java +[source,java,role="primary"] +---- +@ArgGroup MyGroup myGroup = new MyGroup(); +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@ArgGroup var myGroup = MyGroup(); +---- + +The second way is to initialize the objects using business logic, such as `+run+` or `+call+` methods. This way is better if the desired behavior is to allow the application to determine whether the user specified a value for the `+@ArgGroup+`. It is recommended that the program called using `+execute+` instead of `+parseArgs+` + +.Java +[source,java,role="primary"] +---- +@Command(name = "test", description = "demonstrates Default Value declaration") +class MyApp { + @ArgGroup Outer outer; + + static class Outer { + @Options(names = "-x", defaultValue = "XX") String x = "XX"; + @ArgGroup(exclusive = "true") Inner inner; + } + + static class Inner { + @Options(names = "-a", defaultValue = "AA") String a = "AA"; + @Options(names = "-b", defaultValue = "BB") String b = "BB"; + } + + public void run() { + if (outer == null) { // no options specified on command line; apply default values + outer = new Outer; + } + if (outer.inner == null) { // handle nested sub-groups; apply default for inner group + outer.inner = new Inner; + } + + // remaining business logic... + } +} + +public static void main() { + final MyApp obj = new MyApp(); + new CommandLine(obj).execute("-x", "ANOTHER_VALUE"); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- + + import sun.tools.jar.CommandLine@Command(name = "test", description =["demonstrates Default Value declaration"]) +class MyApp { + @ArgGroup lateinit var outer: Outer + + class Outer { + @Options(names = "-x", defaultValue = "XX") var x = "XX"; + @ArgGroup lateinit var inner: Inner + } + + class Inner { + @Options(names = "-a", defaultValue = "AA") var a : "AA" + @Options(names = "-b", defaultValue = "BB") var b : "BB" + } + + override fun run() { + if (outer == null) { // no options specified on command line; apply default values + outer = Outer(); + } + if (outer.inner == null) { // handle nested sub-groups; apply default for inner group + outer.inner = Inner(); + } + + // remaining business logic... + } +} + +fun main(args: Array) { + var obj = MyApp(); + var commandLine = CommandLine(obj); + commandLine.execute(args); +} +---- + + === Positional Parameters When a `@Parameters` positional parameter is part of a group, its `index` is the index _within the group_, not within the command. diff --git a/docs/index.html b/docs/index.html index 2de2bfce3..c7d8dc432 100644 --- a/docs/index.html +++ b/docs/index.html @@ -438,221 +438,6 @@ @media amzn-kf8{#header,#content,#footnotes,#footer{padding:0}} - - - - - @@ -2464,38 +2173,38 @@
Usi
Gradle
-
dependencies {
-    implementation 'info.picocli:picocli:4.6.2'
-    annotationProcessor 'info.picocli:picocli-codegen:4.6.2'
-}
+
dependencies {
+    implementation 'info.picocli:picocli:4.6.3-SNAPSHOT'
+    annotationProcessor 'info.picocli:picocli-codegen:4.6.3-SNAPSHOT'
+}
 
 
-compileJava {
-    options.compilerArgs += ["-Aproject=${project.group}/${project.name}"]
-}
+compileJava { + options.compilerArgs += ["-Aproject=${project.group}/${project.name}"] +}
Maven
-
<plugin>
-  <groupId>org.apache.maven.plugins</groupId>
-  <artifactId>maven-compiler-plugin</artifactId>
-  <!-- annotationProcessorPaths requires maven-compiler-plugin version 3.5 or higher -->
-  <version>${maven-compiler-plugin-version}</version>
-  <configuration>
-    <annotationProcessorPaths>
-      <path>
-        <groupId>info.picocli</groupId>
-        <artifactId>picocli-codegen</artifactId>
-        <version>4.6.2</version>
-      </path>
-    </annotationProcessorPaths>
-    <compilerArgs>
-      <arg>-Aproject=${project.groupId}/${project.artifactId}</arg>
-    </compilerArgs>
-  </configuration>
-</plugin>
+
<plugin>
+  <groupId>org.apache.maven.plugins</groupId>
+  <artifactId>maven-compiler-plugin</artifactId>
+  <!-- annotationProcessorPaths requires maven-compiler-plugin version 3.5 or higher -->
+  <version>${maven-compiler-plugin-version}</version>
+  <configuration>
+    <annotationProcessorPaths>
+      <path>
+        <groupId>info.picocli</groupId>
+        <artifactId>picocli-codegen</artifactId>
+        <version>4.6.3-SNAPSHOT</version>
+      </path>
+    </annotationProcessorPaths>
+    <compilerArgs>
+      <arg>-Aproject=${project.groupId}/${project.artifactId}</arg>
+    </compilerArgs>
+  </configuration>
+</plugin>
@@ -2548,7 +2257,7 @@

-
echo "hello" > hello.txt
+
echo "hello" > hello.txt
@@ -2611,37 +2320,37 @@

3.1. Options

Java
-
class Tar {
-    @Option(names = "-c", description = "create a new archive")
-    boolean create;
+
class Tar {
+    @Option(names = "-c", description = "create a new archive")
+    boolean create;
 
-    @Option(names = { "-f", "--file" }, paramLabel = "ARCHIVE", description = "the archive file")
-    File archive;
+    @Option(names = { "-f", "--file" }, paramLabel = "ARCHIVE", description = "the archive file")
+    File archive;
 
-    @Parameters(paramLabel = "FILE", description = "one ore more files to archive")
-    File[] files;
+    @Parameters(paramLabel = "FILE", description = "one ore more files to archive")
+    File[] files;
 
-    @Option(names = { "-h", "--help" }, usageHelp = true, description = "display a help message")
-    private boolean helpRequested = false;
-}
+ @Option(names = { "-h", "--help" }, usageHelp = true, description = "display a help message") + private boolean helpRequested = false; +}
Kotlin
-
class Tar : Runnable {
-    @Option(names = ["-c"], description = ["create a new archive"])
-    var create: Boolean = false;
+
class Tar : Runnable {
+    @Option(names = ["-c"], description = ["create a new archive"])
+    var create: Boolean = false;
 
-    @Option(names = ["-f", "--file"], paramLabel = "ARCHIVE", description = ["the archive file"])
-    lateinit var archive: File;
+    @Option(names = ["-f", "--file"], paramLabel = "ARCHIVE", description = ["the archive file"])
+    lateinit var archive: File;
 
-    @Parameters(paramLabel = "FILE", description = ["one ore more files to archive"])
-    lateinit var files: Array<File>;
+    @Parameters(paramLabel = "FILE", description = ["one ore more files to archive"])
+    lateinit var files: Array<File>;
 
-    @Option(names = ["-h", "--help"], usageHelp = true, description = ["display a help message"])
-    private var helpRequested: Boolean = false;
-}
+ @Option(names = ["-h", "--help"], usageHelp = true, description = ["display a help message"]) + private var helpRequested: Boolean = false; +}
@@ -2650,27 +2359,27 @@

3.1. Options

Java
-
String[] args = { "-c", "--file", "result.tar", "file1.txt", "file2.txt" };
-Tar tar = new Tar();
-new CommandLine(tar).parseArgs(args);
+
String[] args = { "-c", "--file", "result.tar", "file1.txt", "file2.txt" };
+Tar tar = new Tar();
+new CommandLine(tar).parseArgs(args);
 
-assert !tar.helpRequested;
-assert  tar.create;
-assert  tar.archive.equals(new File("result.tar"));
-assert  Arrays.equals(tar.files, new File[] {new File("file1.txt"), new File("file2.txt")});
+assert !tar.helpRequested; +assert tar.create; +assert tar.archive.equals(new File("result.tar")); +assert Arrays.equals(tar.files, new File[] {new File("file1.txt"), new File("file2.txt")});
Kotlin
-
val args1 = arrayOf("-c", "--file", "result.tar", "file1.txt", "file2.txt")
-var tar = Tar()
-CommandLine(tar).parseArgs(*args1);
+
val args1 = arrayOf("-c", "--file", "result.tar", "file1.txt", "file2.txt")
+var tar = Tar()
+CommandLine(tar).parseArgs(*args1);
 
-assert(!tar.helpRequested)
-assert(tar.create)
-assert(tar.archive.equals(File("result.tar")))
-assert(Arrays.equals(tar.files, arrayOf<File>(File("file1.txt"), File("file2.txt"))))
+assert(!tar.helpRequested) +assert(tar.create) +assert(tar.archive.equals(File("result.tar"))) +assert(Arrays.equals(tar.files, arrayOf<File>(File("file1.txt"), File("file2.txt"))))
@@ -2708,61 +2417,61 @@

3.2.1. Example

Java
-
class Login implements Callable<Integer> {
-    @Option(names = {"-u", "--user"}, description = "User name")
-    String user;
+
class Login implements Callable<Integer> {
+    @Option(names = {"-u", "--user"}, description = "User name")
+    String user;
 
-    @Option(names = {"-p", "--password"}, description = "Passphrase", interactive = true)
-    char[] password;
+    @Option(names = {"-p", "--password"}, description = "Passphrase", interactive = true)
+    char[] password;
 
-    public Integer call() throws Exception {
-        byte[] bytes = new byte[password.length];
-        for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) password[i]; }
+    public Integer call() throws Exception {
+        byte[] bytes = new byte[password.length];
+        for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) password[i]; }
 
-        MessageDigest md = MessageDigest.getInstance("SHA-256");
-        md.update(bytes);
+        MessageDigest md = MessageDigest.getInstance("SHA-256");
+        md.update(bytes);
 
-        System.out.printf("Hi %s, your password is hashed to %s.%n", user, base64(md.digest()));
+        System.out.printf("Hi %s, your password is hashed to %s.%n", user, base64(md.digest()));
 
-        // null out the arrays when done
-        Arrays.fill(bytes, (byte) 0);
-        Arrays.fill(password, ' ');
+        // null out the arrays when done
+        Arrays.fill(bytes, (byte) 0);
+        Arrays.fill(password, ' ');
 
-        return 0;
-    }
+        return 0;
+    }
 
-    private String base64(byte[] arr) { /* ... */ }
-}
+ private String base64(byte[] arr) { /* ... */ } +}
Kotlin
-
class Login : Callable<Int> {
-    @Option(names = ["-u", "--user"], description = ["User name"])
-    var user: String? = null
+
class Login : Callable<Int> {
+    @Option(names = ["-u", "--user"], description = ["User name"])
+    var user: String? = null
 
-    @Option(names = ["-p", "--password"], description = ["Passphrase"], interactive = true)
-    lateinit var password: CharArray
+    @Option(names = ["-p", "--password"], description = ["Passphrase"], interactive = true)
+    lateinit var password: CharArray
 
-    override fun call(): Int {
-        val bytes = ByteArray(password.size)
-        for (i in bytes.indices) { bytes[i] = password[i].toByte() }
+    override fun call(): Int {
+        val bytes = ByteArray(password.size)
+        for (i in bytes.indices) { bytes[i] = password[i].toByte() }
 
-        val md = MessageDigest.getInstance("SHA-256")
-        md.update(bytes)
+        val md = MessageDigest.getInstance("SHA-256")
+        md.update(bytes)
 
-        println(("Hi %s, your password is hashed to %s.").format(user, base64(md.digest())))
+        println(("Hi %s, your password is hashed to %s.").format(user, base64(md.digest())))
 
-        // null out the arrays when done
-        Arrays.fill(bytes, 0.toByte())
-        Arrays.fill(password, ' ')
+        // null out the arrays when done
+        Arrays.fill(bytes, 0.toByte())
+        Arrays.fill(password, ' ')
 
-        return 0
-    }
+        return 0
+    }
 
-    private fun base64(arr: ByteArray): String { /* ... */ }
-}
+ private fun base64(arr: ByteArray): String { /* ... */ } +}
@@ -2771,13 +2480,13 @@

3.2.1. Example

Java
-
new CommandLine(new Login()).execute("-u", "user123", "-p");
+
new CommandLine(new Login()).execute("-u", "user123", "-p");
Kotlin
-
CommandLine(Login()).execute("-u", "user123", "-p")
+
CommandLine(Login()).execute("-u", "user123", "-p")
Kotlin
-
@Option(names = ["--user"])
-lateinit var user: String
+
@Option(names = ["--user"])
+lateinit var user: String
 
-@Option(names = ["--password"], arity = "0..1", interactive = true)
-lateinit var password: CharArray
+@Option(names = ["--password"], arity = "0..1", interactive = true) +lateinit var password: CharArray
@@ -2899,23 +2608,23 @@

Java
-
class ClusteredShortOptions {
-    @Option(names = "-a") boolean aaa;
-    @Option(names = "-b") boolean bbb;
-    @Option(names = "-c") boolean ccc;
-    @Option(names = "-f") String  file;
-}
+
class ClusteredShortOptions {
+    @Option(names = "-a") boolean aaa;
+    @Option(names = "-b") boolean bbb;
+    @Option(names = "-c") boolean ccc;
+    @Option(names = "-f") String  file;
+}

Kotlin
-
class ClusteredShortOptions {
-    @Option(names = ["-a"]) var aaa = false
-    @Option(names = ["-b"]) var bbb = false
-    @Option(names = ["-c"]) var ccc = false
-    @Option(names = ["-f"]) lateinit var file: String
-}
+
class ClusteredShortOptions {
+    @Option(names = ["-a"]) var aaa = false
+    @Option(names = ["-b"]) var bbb = false
+    @Option(names = ["-c"]) var ccc = false
+    @Option(names = ["-f"]) lateinit var file: String
+}
@@ -2923,13 +2632,13 @@

-
<command> -abcfInputFile.txt
-<command> -abcf=InputFile.txt
-<command> -abc -f=InputFile.txt
-<command> -ab -cf=InputFile.txt
-<command> -a -b -c -fInputFile.txt
-<command> -a -b -c -f InputFile.txt
-<command> -a -b -c -f=InputFile.txt
+
<command> -abcfInputFile.txt
+<command> -abcf=InputFile.txt
+<command> -abc -f=InputFile.txt
+<command> -ab -cf=InputFile.txt
+<command> -a -b -c -fInputFile.txt
+<command> -a -b -c -f InputFile.txt
+<command> -a -b -c -f=InputFile.txt
 ...
@@ -2958,17 +2667,17 @@

3.4. Bo
Java
-
class BooleanOptions {
-    @Option(names = "-x") boolean x;
-}
+
class BooleanOptions {
+    @Option(names = "-x") boolean x;
+}
Kotlin
-
class BooleanOptions {
-    @Option(names = ["-x"]) var x = false
-}
+
class BooleanOptions {
+    @Option(names = ["-x"]) var x = false
+}
@@ -3003,23 +2712,23 @@

3.5
Java
-
@Command(name = "negatable-options-demo")
-class NegatableOptionsDemo {
-    @Option(names = "--verbose",           negatable = true) boolean verbose;
-    @Option(names = "-XX:+PrintGCDetails", negatable = true) boolean printGCDetails;
-    @Option(names = "-XX:-UseG1GC",        negatable = true) boolean useG1GC = true;
-}
+
@Command(name = "negatable-options-demo")
+class NegatableOptionsDemo {
+    @Option(names = "--verbose",           negatable = true) boolean verbose;
+    @Option(names = "-XX:+PrintGCDetails", negatable = true) boolean printGCDetails;
+    @Option(names = "-XX:-UseG1GC",        negatable = true) boolean useG1GC = true;
+}
Kotlin
-
@Command(name = "negatable-options-demo")
-class NegatableOptionsDemo {
-    @Option(names = ["--verbose"],           negatable = true) var verbose = false
-    @Option(names = ["-XX:+PrintGCDetails"], negatable = true) var printGCDetails = false
-    @Option(names = ["-XX:-UseG1GC"],        negatable = true) var useG1GC = true
-}
+
@Command(name = "negatable-options-demo")
+class NegatableOptionsDemo {
+    @Option(names = ["--verbose"],           negatable = true) var verbose = false
+    @Option(names = ["-XX:+PrintGCDetails"], negatable = true) var printGCDetails = false
+    @Option(names = ["-XX:-UseG1GC"],        negatable = true) var useG1GC = true
+}
@@ -3060,17 +2769,17 @@

3.5
Java
-
@Option(names = "--no-backup", negatable = true,
-  description = "Make a backup. True by default.")
-boolean backup = true;
+
@Option(names = "--no-backup", negatable = true,
+  description = "Make a backup. True by default.")
+boolean backup = true;
Kotlin
-
@Option(names = ["--no-backup"], negatable = true,
-  description = ["Make a backup. True by default."])
-var backup = true
+
@Option(names = ["--no-backup"], negatable = true,
+  description = ["Make a backup. True by default."])
+var backup = true
@@ -3105,27 +2814,27 @@

3.6.1. Ex
Java
-
class PositionalParameters {
-    @Parameters(index = "0")    InetAddress host;
-    @Parameters(index = "1")    int port;
-    @Parameters(index = "2..*") File[] files;
+
class PositionalParameters {
+    @Parameters(index = "0")    InetAddress host;
+    @Parameters(index = "1")    int port;
+    @Parameters(index = "2..*") File[] files;
 
-    @Parameters(hidden = true)  // "hidden": don't show this parameter in usage help message
-    List<String> allParameters; // no "index" attribute: captures _all_ arguments
-}
+ @Parameters(hidden = true) // "hidden": don't show this parameter in usage help message + List<String> allParameters; // no "index" attribute: captures _all_ arguments +}
Kotlin
-
class PositionalParameters {
-    @Parameters(index = "0")    lateinit var host: InetAddress
-    @Parameters(index = "1")    var port = 0
-    @Parameters(index = "2..*") lateinit var files: Array<File>
+
class PositionalParameters {
+    @Parameters(index = "0")    lateinit var host: InetAddress
+    @Parameters(index = "1")    var port = 0
+    @Parameters(index = "2..*") lateinit var files: Array<File>
 
-    @Parameters(hidden = true)   // "hidden": don't show this parameter in usage help message
-    lateinit var allParameters: List<String> // no "index" attribute: captures _all_ arguments
-}
+ @Parameters(hidden = true) // "hidden": don't show this parameter in usage help message + lateinit var allParameters: List<String> // no "index" attribute: captures _all_ arguments +}
@@ -3134,27 +2843,27 @@

3.6.1. Ex
Java
-
String[] args = { "localhost", "12345", "file1.txt", "file2.txt" };
-PositionalParameters params = CommandLine.populateCommand(new PositionalParameters(), args);
+
String[] args = { "localhost", "12345", "file1.txt", "file2.txt" };
+PositionalParameters params = CommandLine.populateCommand(new PositionalParameters(), args);
 
-assert params.host.getHostName().equals("localhost");
-assert params.port == 12345;
-assert Arrays.equals(params.files, new File[] {new File("file1.txt"), new File("file2.txt")});
+assert params.host.getHostName().equals("localhost");
+assert params.port == 12345;
+assert Arrays.equals(params.files, new File[] {new File("file1.txt"), new File("file2.txt")});
 
-assert params.allParameters.equals(Arrays.asList(args));
+assert params.allParameters.equals(Arrays.asList(args));
Kotlin
-
val args = arrayOf("localhost", "12345", "file1.txt", "file2.txt")
-val params: PositionalParameters = CommandLine.populateCommand(PositionalParameters(), *args)
+
val args = arrayOf("localhost", "12345", "file1.txt", "file2.txt")
+val params: PositionalParameters = CommandLine.populateCommand(PositionalParameters(), *args)
 
-assert(params.host.getHostName().equals("localhost"))
-assert(params.port === 12345)
-assert(Arrays.equals(params.files, arrayOf(File("file1.txt"), File("file2.txt"))))
+assert(params.host.getHostName().equals("localhost"))
+assert(params.port === 12345)
+assert(Arrays.equals(params.files, arrayOf(File("file1.txt"), File("file2.txt"))))
 
-assert(params.allParameters.equals(Arrays.asList(*args)))
+assert(params.allParameters.equals(Arrays.asList(*args)))
Kotlin
-
class Mixed {
-    @Parameters
-    lateinit var positional: List<String>
+
class Mixed {
+    @Parameters
+    lateinit var positional: List<String>
 
-    @Option(names = ["-o"])
-    lateinit var options: List<String>
-}
+ @Option(names = ["-o"]) + lateinit var options: List<String> +}
Kotlin
-
val args = arrayOf("param0", "-o", "AAA", "param1", "param2", "-o", "BBB", "param3")
-val mixed = Mixed()
-CommandLine(mixed).parseArgs(*args)
+
val args = arrayOf("param0", "-o", "AAA", "param1", "param2", "-o", "BBB", "param3")
+val mixed = Mixed()
+CommandLine(mixed).parseArgs(*args)
 
-assert(mixed.positional == Arrays.asList("param0", "param1", "param2", "param3"))
-assert(mixed.options == Arrays.asList("AAA", "BBB"))
+assert(mixed.positional == Arrays.asList("param0", "param1", "param2", "param3")) +assert(mixed.options == Arrays.asList("AAA", "BBB"))

@@ -3277,21 +2986,21 @@

3.8. Double das
Java
-
class DoubleDashDemo {
-    @Option(names = "-v")     boolean verbose;
-    @Option(names = "-files") List<String> files;
-    @Parameters               List<String> params;
-}
+
class DoubleDashDemo {
+    @Option(names = "-v")     boolean verbose;
+    @Option(names = "-files") List<String> files;
+    @Parameters               List<String> params;
+}
Kotlin
-
class DoubleDashDemo {
-    @Option(names = ["-v"])     var verbose = false
-    @Option(names = ["-files"]) var files: List<String>? = null
-    @Parameters                 lateinit var params: List<String>
-}
+
class DoubleDashDemo {
+    @Option(names = ["-v"])     var verbose = false
+    @Option(names = ["-files"]) var files: List<String>? = null
+    @Parameters                 lateinit var params: List<String>
+}
@@ -3300,25 +3009,25 @@

3.8. Double das
Java
-
String[] args = { "-v", "--", "-files", "file1", "file2" };
-DoubleDashDemo demo = new DoubleDashDemo();
-new CommandLine(demo).parseArgs(args);
+
String[] args = { "-v", "--", "-files", "file1", "file2" };
+DoubleDashDemo demo = new DoubleDashDemo();
+new CommandLine(demo).parseArgs(args);
 
-assert demo.verbose;
-assert demo.files == null;
-assert demo.params.equals(Arrays.asList("-files", "file1", "file2"));
+assert demo.verbose; +assert demo.files == null; +assert demo.params.equals(Arrays.asList("-files", "file1", "file2"));
Kotlin
-
val args = arrayOf("-v", "--", "-files", "file1", "file2")
-val demo = DoubleDashDemo()
-CommandLine(demo).parseArgs(*args)
+
val args = arrayOf("-v", "--", "-files", "file1", "file2")
+val demo = DoubleDashDemo()
+CommandLine(demo).parseArgs(*args)
 
-assert(demo.verbose)
-assert(demo.files == null)
-assert(demo.params == Arrays.asList("-files", "file1", "file2"))
+assert(demo.verbose) +assert(demo.files == null) +assert(demo.params == Arrays.asList("-files", "file1", "file2"))
Kotlin
-
class App {
-    @Option(names = ["-a"], converter = [CipherConverter::class])
-    lateinit var cipher: javax.crypto.Cipher
-}
+
class App {
+    @Option(names = ["-a"], converter = [CipherConverter::class])
+    lateinit var cipher: javax.crypto.Cipher
+}
Groovy
-
class App {
-    @Option(names = "-a", converter = CipherConverter.class)
-    def cipher
-}
+
class App {
+    @Option(names = "-a", converter = CipherConverter.class)
+    def cipher
+}
Groovy Script
-
class App {
-    @Option(names = "-a", converter = [ // requires Groovy 3.0.7
-            { { str -> Cipher.getInstance(str) } as ITypeConverter }
-    ])
-    def cipher
-}
+
class App {
+    @Option(names = "-a", converter = [ // requires Groovy 3.0.7
+            { { str -> Cipher.getInstance(str) } as ITypeConverter }
+    ])
+    def cipher
+}
Kotlin
-
import java.util.Locale
-import javax.crypto.Cipher
-// ...
+
import java.util.Locale
+import javax.crypto.Cipher
+// ...
 
-class App {
-    @Parameters
-    lateinit var locale: Locale
+class App {
+    @Parameters
+    lateinit var locale: Locale
 
-    @Option(names = ["-a"])
-    lateinit var cipher: Cipher
-}
+ @Option(names = ["-a"]) + lateinit var cipher: Cipher +}
Kotlin
-
val app = App()
-val commandLine = CommandLine(app)
-    .registerConverter(Locale::class.java) {
-        s: String? -> Locale.Builder().setLanguageTag(s).build()
-    }
-    .registerConverter(Cipher::class.java) {
-        Cipher.getInstance(it)
-    }
+
val app = App()
+val commandLine = CommandLine(app)
+    .registerConverter(Locale::class.java) {
+        s: String? -> Locale.Builder().setLanguageTag(s).build()
+    }
+    .registerConverter(Cipher::class.java) {
+        Cipher.getInstance(it)
+    }
 
-commandLine.parseArgs("-a", "AES/CBC/NoPadding", "en-GB")
-assert(app.locale.toLanguageTag() == "en-GB")
-assert(app.cipher.algorithm == "AES/CBC/NoPadding")
+commandLine.parseArgs("-a", "AES/CBC/NoPadding", "en-GB") +assert(app.locale.toLanguageTag() == "en-GB") +assert(app.cipher.algorithm == "AES/CBC/NoPadding")
Kotlin
-
@Command(name = "set-position")
-class SetPositionCommand {
-    @Parameters(parameterConsumer = PointConverter::class)
-    private lateinit var position: Point
-
-    class PointConverter : IParameterConsumer {
-        override fun consumeParameters(args: Stack<String>,
-                                       argSpec: ArgSpec,
-                                       commandSpec: CommandSpec) {
-            if (args.size < 2) {
-                throw ParameterException(commandSpec.commandLine(),
-                    "Missing coordinates for Point. Please specify 2 coordinates.")
-            }
-            val x = args.pop().toInt()
-            val y = args.pop().toInt()
-            argSpec.setValue(Point(x, y))
-        }
-    }
-}
+
@Command(name = "set-position")
+class SetPositionCommand {
+    @Parameters(parameterConsumer = PointConverter::class)
+    private lateinit var position: Point
+
+    class PointConverter : IParameterConsumer {
+        override fun consumeParameters(args: Stack<String>,
+                                       argSpec: ArgSpec,
+                                       commandSpec: CommandSpec) {
+            if (args.size < 2) {
+                throw ParameterException(commandSpec.commandLine(),
+                    "Missing coordinates for Point. Please specify 2 coordinates.")
+            }
+            val x = args.pop().toInt()
+            val y = args.pop().toInt()
+            argSpec.setValue(Point(x, y))
+        }
+    }
+}
Kotlin
-
import java.net.InetSocketAddress
-// ...
+
import java.net.InetSocketAddress
+// ...
 
-class InetSocketAddressConverter : ITypeConverter<InetSocketAddress> {
-    override fun convert(value: String): InetSocketAddress {
-        val pos = value.lastIndexOf(':')
-        if (pos < 0) {
-            throw CommandLine.TypeConversionException(
-                "Invalid format: must be 'host:port' but was '$value'")
-        }
-        val adr = value.substring(0, pos)
-        val port = value.substring(pos + 1).toInt()
-        return InetSocketAddress(adr, port)
-    }
-}
+class InetSocketAddressConverter : ITypeConverter<InetSocketAddress> { + override fun convert(value: String): InetSocketAddress { + val pos = value.lastIndexOf(':') + if (pos < 0) { + throw CommandLine.TypeConversionException( + "Invalid format: must be 'host:port' but was '$value'") + } + val adr = value.substring(0, pos) + val port = value.substring(pos + 1).toInt() + return InetSocketAddress(adr, port) + } +}
Kotlin
-
class App {
-    @Option(names = ["--sqlType"], converter = [SqlTypeConverter::class])
-    var sqlType = 0
-}
+
class App {
+    @Option(names = ["--sqlType"], converter = [SqlTypeConverter::class])
+    var sqlType = 0
+}
Kotlin
-
class SqlTypeConverter : ITypeConverter<Int> {
-    @Throws(Exception::class)
-    override fun convert(value: String): Int {
-        when (value) {
-            "ARRAY"  -> return Types.ARRAY
-            "BIGINT" -> return Types.BIGINT
-            "BINARY" -> return Types.BINARY
-            "BIT"    -> return Types.BIT
-            "BLOB"   -> return Types.BLOB
-            // ...
-        }
-    }
-}
+
class SqlTypeConverter : ITypeConverter<Int> {
+    @Throws(Exception::class)
+    override fun convert(value: String): Int {
+        when (value) {
+            "ARRAY"  -> return Types.ARRAY
+            "BIGINT" -> return Types.BIGINT
+            "BINARY" -> return Types.BINARY
+            "BIT"    -> return Types.BIT
+            "BLOB"   -> return Types.BLOB
+            // ...
+        }
+    }
+}
Kotlin
-
import java.io.File
-import java.util.regex.Pattern
-// ...
+
import java.io.File
+import java.util.regex.Pattern
+// ...
 
-class Convert {
-    @Option(names = ["-patterns"], description = ["the regex patterns to use"])
-    lateinit var patterns: Array<Pattern>
+class Convert {
+    @Option(names = ["-patterns"], description = ["the regex patterns to use"])
+    lateinit var patterns: Array<Pattern>
 
-    @Parameters( /* type = [File::class], */ description = ["the files to convert"])
-    lateinit var files: List<File> // picocli infers type from the generic type
-}
+ @Parameters( /* type = [File::class], */ description = ["the files to convert"]) + lateinit var files: List<File> // picocli infers type from the generic type +}
Java
-
String[] args = { "-patterns", "a*b", "-patterns", "[a-e][i-u]", "file1.txt", "file2.txt" };
-Convert convert = CommandLine.populateCommand(new Convert(), args);
+
String[] args = { "-patterns", "a*b", "-patterns", "[a-e][i-u]", "file1.txt", "file2.txt" };
+Convert convert = CommandLine.populateCommand(new Convert(), args);
 
-// convert.patterns now has two Pattern objects
-// convert.files now has two File objects
+// convert.patterns now has two Pattern objects +// convert.files now has two File objects
Kotlin
-
val args = arrayOf("-patterns", "a*b", "-patterns", "[a-e][i-u]", "file1.txt", "file2.txt")
-val convert = CommandLine.populateCommand(Convert(), *args)
+
val args = arrayOf("-patterns", "a*b", "-patterns", "[a-e][i-u]", "file1.txt", "file2.txt")
+val convert = CommandLine.populateCommand(Convert(), *args)
 
-// convert.patterns now has two Pattern objects
-// convert.files now has two File objects
+// convert.patterns now has two Pattern objects +// convert.files now has two File objects
@@ -4066,34 +3775,34 @@

4.5.2. Maps

Java
-
import java.net.InetAddress;
-import java.net.Proxy.Type;
-import java.util.concurrent.TimeUnit;
+
import java.net.InetAddress;
+import java.net.Proxy.Type;
+import java.util.concurrent.TimeUnit;
 
-class MapDemo {
-    @Option(names = {"-p", "--proxyHost"})
-    Map<Proxy.Type, InetAddress> proxies;
+class MapDemo {
+    @Option(names = {"-p", "--proxyHost"})
+    Map<Proxy.Type, InetAddress> proxies;
 
-    @Option(names = {"-u", "--timeUnit"})
-    Map<TimeUnit, Long> timeout;
-}
+ @Option(names = {"-u", "--timeUnit"}) + Map<TimeUnit, Long> timeout; +}
Kotlin
-
import java.net.InetAddress
-import java.net.Proxy
-import java.util.concurrent.TimeUnit
-// ...
+
import java.net.InetAddress
+import java.net.Proxy
+import java.util.concurrent.TimeUnit
+// ...
 
-class MapDemo {
-    @Option(names = ["-p", "--proxyHost"])
-    lateinit var proxies: Map<Proxy.Type, InetAddress>
+class MapDemo {
+    @Option(names = ["-p", "--proxyHost"])
+    lateinit var proxies: Map<Proxy.Type, InetAddress>
 
-    @Option(names = ["-u", "--timeUnit"])
-    lateinit var timeout: Map<TimeUnit, Long>
-}
+ @Option(names = ["-u", "--timeUnit"]) + lateinit var timeout: Map<TimeUnit, Long> +}
@@ -4101,8 +3810,8 @@

4.5.2. Maps

-
<command> -p HTTP=123.123.123.123 --proxyHost SOCKS=212.212.212.212
-<command> -uDAYS=3 -u HOURS=23 -u=MINUTES=59 --timeUnit=SECONDS=13
+
<command> -p HTTP=123.123.123.123 --proxyHost SOCKS=212.212.212.212
+<command> -uDAYS=3 -u HOURS=23 -u=MINUTES=59 --timeUnit=SECONDS=13
Kotlin
-
@Option(names = ["-P", "--properties"], mapFallbackValue = Option.NULL_VALUE)
-lateinit var properties: Map<String, Optional<Int>>
+
@Option(names = ["-P", "--properties"], mapFallbackValue = Option.NULL_VALUE)
+lateinit var properties: Map<String, Optional<Int>>
 
-@Parameters(mapFallbackValue = "INFO", description = "... ${MAP-FALLBACK-VALUE} ...")
-lateinit var logLevels: Map<Class<?>, LogLevel>
+@Parameters(mapFallbackValue = "INFO", description = "... ${MAP-FALLBACK-VALUE} ...") +lateinit var logLevels: Map<Class<?>, LogLevel>
@@ -4192,23 +3901,23 @@

4.5
Java
-
class SystemPropertiesDemo {
-    @Option(names = "-D", mapFallbackValue = "") // allow -Dkey
-    void setProperty(Map<String, String> props) {
-        props.forEach((k, v) -> System.setProperty(k, v));
-    }
-}
+
class SystemPropertiesDemo {
+    @Option(names = "-D", mapFallbackValue = "") // allow -Dkey
+    void setProperty(Map<String, String> props) {
+        props.forEach((k, v) -> System.setProperty(k, v));
+    }
+}
Kotlin
-
class SystemPropertiesDemo {
-    @Option(names = ["-D"], mapFallbackValue = "") // allow -Dkey
-    fun setProperty(props: Map<String, String>) {
-        props.forEach { (k: String, v: String) -> System.setProperty(k, v) }
-    }
-}
+
class SystemPropertiesDemo {
+    @Option(names = ["-D"], mapFallbackValue = "") // allow -Dkey
+    fun setProperty(props: Map<String, String>) {
+        props.forEach { (k: String, v: String) -> System.setProperty(k, v) }
+    }
+}

@@ -4223,21 +3932,21 @@

4.6. Optional<T&
Java
-
@Option(names = "-x")
-Optional<Integer> x;
+
@Option(names = "-x")
+Optional<Integer> x;
 
-@Option(names = "-D", mapFallbackValue = Option.NULL_VALUE)
-Map<String, Optional<Integer>> map;
+@Option(names = "-D", mapFallbackValue = Option.NULL_VALUE) +Map<String, Optional<Integer>> map;
Kotlin
-
@Option(names = ["-x"])
-lateinit var x: Optional<Int>
+
@Option(names = ["-x"])
+lateinit var x: Optional<Int>
 
-@Option(names = ["-D"], mapFallbackValue = Option.NULL_VALUE)
-lateinit var map: Map<String, Optional<Int>>
+@Option(names = ["-D"], mapFallbackValue = Option.NULL_VALUE) +lateinit var map: Map<String, Optional<Int>>
@@ -4265,31 +3974,31 @@

<
Java
-
class App {
-    @Option(names = "--big", type = BigDecimal.class) // concrete Number subclass
-    Number[] big; // array type with abstract component class
+
class App {
+    @Option(names = "--big", type = BigDecimal.class) // concrete Number subclass
+    Number[] big; // array type with abstract component class
 
-    @Option(names = "--small", type = Short.class) // other Number subclass
-    Number[] small;
+    @Option(names = "--small", type = Short.class) // other Number subclass
+    Number[] small;
 
-    @Parameters(type = StringBuilder.class) // StringBuilder implements CharSequence
-    CharSequence address; // interface type
-}
+ @Parameters(type = StringBuilder.class) // StringBuilder implements CharSequence + CharSequence address; // interface type +}
Kotlin
-
class App {
-    @Option(names = ["--big"], type = [BigDecimal::class]) // concrete Number subclass
-    lateinit var big: Array<Number> // array type with abstract component class
+
class App {
+    @Option(names = ["--big"], type = [BigDecimal::class]) // concrete Number subclass
+    lateinit var big: Array<Number> // array type with abstract component class
 
-    @Option(names = ["--small"], type = [Short::class]) // other Number subclass
-    lateinit var small: Array<Number>
+    @Option(names = ["--small"], type = [Short::class]) // other Number subclass
+    lateinit var small: Array<Number>
 
-    @Parameters(type = [StringBuilder::class]) // StringBuilder implements CharSequence
-    lateinit var address: CharSequence // interface type
-}
+ @Parameters(type = [StringBuilder::class]) // StringBuilder implements CharSequence + lateinit var address: CharSequence // interface type +}
Kotlin
-
class TypeDemo {
-    @Option(names = ["-x"])              // not enough information to convert
-    lateinit var weaklyTyped: Map<*, *> // String keys and values are added as is
+
class TypeDemo {
+    @Option(names = ["-x"])              // not enough information to convert
+    lateinit var weaklyTyped: Map<*, *> // String keys and values are added as is
 
-    @Option(names = ["-y"], type = [Short::class, BigDecimal::class])
-    lateinit var stronglyTyped: Map<out Number, Number>
+    @Option(names = ["-y"], type = [Short::class, BigDecimal::class])
+    lateinit var stronglyTyped: Map<out Number, Number>
 
-    @Option(names = ["-s"], type = [CharBuffer::class])
-    lateinit var text: List<CharSequence>
-}
+ @Option(names = ["-s"], type = [CharBuffer::class]) + lateinit var text: List<CharSequence> +}

@@ -4364,19 +4073,19 @@

Java
-
interface Spec {
-    @Option(names = "-c", defaultValue = "123", description = "... ${DEFAULT-VALUE} ...")
-    int count();
-}
+
interface Spec {
+    @Option(names = "-c", defaultValue = "123", description = "... ${DEFAULT-VALUE} ...")
+    int count();
+}

Kotlin
-
interface Spec {
-    @Option(names = ["-c"], defaultValue = "123", description = ["... \${DEFAULT-VALUE} ..."])
-    fun count(): Int
-}
+
interface Spec {
+    @Option(names = ["-c"], defaultValue = "123", description = ["... \${DEFAULT-VALUE} ..."])
+    fun count(): Int
+}
Kotlin
-
class CommandMethod {
-    @Command(description = ["Do something."])
-    fun doit(@Option(names = ["-c"], defaultValue = "123") count: Int) {
-        // ...
-    }
-}
+
class CommandMethod {
+    @Command(description = ["Do something."])
+    fun doit(@Option(names = ["-c"], defaultValue = "123") count: Int) {
+        // ...
+    }
+}
@@ -4416,15 +4125,15 @@

5.2. Field Va
Java
-
@Option(names = "-c", description = "The count (default: ${DEFAULT-VALUE})")
-int count = 123; // default value is 123
+
@Option(names = "-c", description = "The count (default: ${DEFAULT-VALUE})")
+int count = 123; // default value is 123
Kotlin
-
@Option(names = ["-c"], description = ["The count (default: \${DEFAULT-VALUE})"])
-var count = 123 // default value is 123
+
@Option(names = ["-c"], description = ["The count (default: \${DEFAULT-VALUE})"])
+var count = 123 // default value is 123
@@ -4460,15 +4169,15 @@

5.3.
Java
-
@Command(defaultValueProvider = MyDefaultProvider.class)
-class MyCommand // ...
+
@Command(defaultValueProvider = MyDefaultProvider.class)
+class MyCommand // ...
Kotlin
-
@Command(defaultValueProvider = MyDefaultProvider::class)
-class MyCommand // ...
+
@Command(defaultValueProvider = MyDefaultProvider::class)
+class MyCommand // ...
@@ -4477,9 +4186,9 @@

5.3.

-
public interface IDefaultValueProvider {
+
public interface IDefaultValueProvider {
 
-    /**
+    /**
      * Returns the default value for an option or positional parameter or {@code null}.
      * The returned value is converted to the type of the option/positional parameter
      * via the same type converter used when populating this option/positional
@@ -4489,9 +4198,9 @@ 

5.3. * @return the default value for the option or positional parameter, or {@code null} if * this provider has no default value for the specified option or positional parameter * @throws Exception when there was a problem obtaining the default value - */ - String defaultValue(ArgSpec argSpec) throws Exception; -}

+ */ + String defaultValue(ArgSpec argSpec) throws Exception; +}
Kotlin
-
import picocli.CommandLine.PropertiesDefaultProvider;
-// ...
-@Command(name = "git", defaultValueProvider = PropertiesDefaultProvider::class)
-class Git { }
+
import picocli.CommandLine.PropertiesDefaultProvider;
+// ...
+@Command(name = "git", defaultValueProvider = PropertiesDefaultProvider::class)
+class Git { }
Kotlin
-
val cmd = CommandLine(MyCommand())
-val defaultsFile = File("path/to/config/mycommand.properties")
-cmd.defaultValueProvider = PropertiesDefaultProvider(defaultsFile)
-cmd.execute(*args)
+
val cmd = CommandLine(MyCommand())
+val defaultsFile = File("path/to/config/mycommand.properties")
+cmd.defaultValueProvider = PropertiesDefaultProvider(defaultsFile)
+cmd.execute(*args)
Kotlin
-
class FallbackValueDemo : Runnable {
-    @Option(names = ["-x"], arity = "0..1",
-            defaultValue = "-1", fallbackValue = "-2",
-            description = ["Option with optional parameter. Default: \${DEFAULT-VALUE}, " +
-                           "if specified without parameter: \${FALLBACK-VALUE}"])
-    var x = 0
+
class FallbackValueDemo : Runnable {
+    @Option(names = ["-x"], arity = "0..1",
+            defaultValue = "-1", fallbackValue = "-2",
+            description = ["Option with optional parameter. Default: \${DEFAULT-VALUE}, " +
+                           "if specified without parameter: \${FALLBACK-VALUE}"])
+    var x = 0
 
-    override fun run() { println("x = $x") }
-}
+    override fun run() { println("x = $x") }
+}
 
-fun main(args: Array<String>) {
-    CommandLine(FallbackValueDemo()).execute(*args)
-}
+fun main(args: Array<String>) { + CommandLine(FallbackValueDemo()).execute(*args) +}
@@ -4680,68 +4389,68 @@

Java
-
@Command(name = "defaults", mixinStandardHelpOptions = true, version = "defaults 0.1")
-public class DefaultValueDemo implements Runnable {
+
@Command(name = "defaults", mixinStandardHelpOptions = true, version = "defaults 0.1")
+public class DefaultValueDemo implements Runnable {
 
-    @Option(names = "-x")
-    int x = 10;
+    @Option(names = "-x")
+    int x = 10;
 
-    @Option(names = "-y", defaultValue = "20")
-    int y;
+    @Option(names = "-y", defaultValue = "20")
+    int y;
 
-    @Spec CommandSpec spec;
+    @Spec CommandSpec spec;
 
-    @Override
-    public void run() {
-        ParseResult pr = spec.commandLine().getParseResult();
+    @Override
+    public void run() {
+        ParseResult pr = spec.commandLine().getParseResult();
 
-        for (OptionSpec option : spec.options()) {
-            String name = option.longestName();
-            System.out.printf("%s was specified: %s%n", name, pr.hasMatchedOption(option));
-            System.out.printf("%s=%s (-1 means this option was not matched on command line)%n",
-                    name, pr.matchedOptionValue(name, -1));
-            System.out.printf("%s=%s (arg value or default)%n", name, option.getValue());
-            System.out.println();
-        }
-    }
+        for (OptionSpec option : spec.options()) {
+            String name = option.longestName();
+            System.out.printf("%s was specified: %s%n", name, pr.hasMatchedOption(option));
+            System.out.printf("%s=%s (-1 means this option was not matched on command line)%n",
+                    name, pr.matchedOptionValue(name, -1));
+            System.out.printf("%s=%s (arg value or default)%n", name, option.getValue());
+            System.out.println();
+        }
+    }
 
-    public static void main(String[] args) {
-        new CommandLine(new DefaultValueDemo()).execute(args);
-    }
-}
+ public static void main(String[] args) { + new CommandLine(new DefaultValueDemo()).execute(args); + } +}

Kotlin
-
@Command(name = "defaults", mixinStandardHelpOptions = true, version = ["defaults 0.1"])
-class DefaultValueDemo<T> : Runnable {
+
@Command(name = "defaults", mixinStandardHelpOptions = true, version = ["defaults 0.1"])
+class DefaultValueDemo<T> : Runnable {
 
-    @Option(names = ["-x"])
-    var x = 10
+    @Option(names = ["-x"])
+    var x = 10
 
-    @Option(names = ["-y"], defaultValue = "20")
-    var y = 0
+    @Option(names = ["-y"], defaultValue = "20")
+    var y = 0
 
-    @Spec lateinit var spec: CommandSpec
+    @Spec lateinit var spec: CommandSpec
 
-    override fun run() {
-        val pr: ParseResult = spec.commandLine().parseResult
+    override fun run() {
+        val pr: ParseResult = spec.commandLine().parseResult
 
-        for (option in spec.options()) {
-            val name = option.longestName()
-            println("$name was specified: ${pr.hasMatchedOption(option)}")
-            println("$name=${pr.matchedOptionValue(name, -1)} " +
-                    "(-1 means this option was not matched on command line)")
-            println("$name=${option.getValue<T>()} (arg value or default)")
-            println()
-        }
-    }
-}
+        for (option in spec.options()) {
+            val name = option.longestName()
+            println("$name was specified: ${pr.hasMatchedOption(option)}")
+            println("$name=${pr.matchedOptionValue(name, -1)} " +
+                    "(-1 means this option was not matched on command line)")
+            println("$name=${option.getValue<T>()} (arg value or default)")
+            println()
+        }
+    }
+}
 
-fun main(args: Array<String>) {
-    CommandLine(DefaultValueDemo<Any>()).execute(*args)
-}
+fun main(args: Array<String>) { + CommandLine(DefaultValueDemo<Any>()).execute(*args) +}

@@ -4763,15 +4472,15 @@

6.1.1
Java
-
@Option(names = "-option")
-int[] values;
+
@Option(names = "-option")
+int[] values;
Kotlin
-
@Option(names = ["-option"])
-lateinit var values: IntArray
+
@Option(names = ["-option"])
+lateinit var values: IntArray
Kotlin
-
@Parameters
-lateinit var units: List<TimeUnit>
+
@Parameters
+lateinit var units: List<TimeUnit>
Kotlin
-
@Option(names = ["-v"], description = ["Specify multiple -v options to increase verbosity.",
-                                        "For example, `-v -v -v` or `-vvv`"])
-lateinit var verbosity: BooleanArray
+
@Option(names = ["-v"], description = ["Specify multiple -v options to increase verbosity.",
+                                        "For example, `-v -v -v` or `-vvv`"])
+lateinit var verbosity: BooleanArray
@@ -4860,15 +4569,15 @@

6.2. Split Rege
Java
-
@Option(names = "-option", split = ",")
-int[] values;
+
@Option(names = "-option", split = ",")
+int[] values;
Kotlin
-
@Option(names = ["-option"], split = ",")
-lateinit var values: IntArray
+
@Option(names = ["-option"], split = ",")
+lateinit var values: IntArray
@@ -4885,15 +4594,15 @@

6.2. Split Rege
Java
-
@Option(names = "-fix", split = "\\|", splitSynopsisLabel = "|")
-Map<Integer, String> message;
+
@Option(names = "-fix", split = "\\|", splitSynopsisLabel = "|")
+Map<Integer, String> message;
Kotlin
-
@Option(names = ["-fix"], split = "\\|", splitSynopsisLabel = "|")
-lateinit var message: Map<Int, String>
+
@Option(names = ["-fix"], split = "\\|", splitSynopsisLabel = "|")
+lateinit var message: Map<Int, String>
@@ -4936,31 +4645,31 @@

6.3. Arity

Java
-
class ArityDemo {
-    @Parameters(arity = "1..3", description = "one to three Files")
-    File[] files;
+
class ArityDemo {
+    @Parameters(arity = "1..3", description = "one to three Files")
+    File[] files;
 
-    @Option(names = "-f", arity = "2", description = "exactly two floating point numbers")
-    double[] doubles;
+    @Option(names = "-f", arity = "2", description = "exactly two floating point numbers")
+    double[] doubles;
 
-    @Option(names = "-s", arity = "1..*", description = "at least one string")
-    String[] strings;
-}
+ @Option(names = "-s", arity = "1..*", description = "at least one string") + String[] strings; +}
Kotlin
-
class ArityDemo {
-    @Parameters(arity = "1..3", description = ["one to three Files"])
-    lateinit var files: Array<File>
+
class ArityDemo {
+    @Parameters(arity = "1..3", description = ["one to three Files"])
+    lateinit var files: Array<File>
 
-    @Option(names = ["-f"], arity = "2", description = ["exactly two floating point numbers"])
-    lateinit var doubles: DoubleArray
+    @Option(names = ["-f"], arity = "2", description = ["exactly two floating point numbers"])
+    lateinit var doubles: DoubleArray
 
-    @Option(names = ["-s"], arity = "1..*", description = ["at least one string"])
-    lateinit var strings: Array<String>
-}
+ @Option(names = ["-s"], arity = "1..*", description = ["at least one string"]) + lateinit var strings: Array<String> +}
Kotlin
-
class Ambiguous {
-    @Parameters(description = ["The file (required)."])
-    lateinit var file: File
+
class Ambiguous {
+    @Parameters(description = ["The file (required)."])
+    lateinit var file: File
 
-    @Option(names = ["-y"], arity = "0..*",
-      description = ["Option with optional parameters"])
-    lateinit var values: List<String>
-}
+ @Option(names = ["-y"], arity = "0..*", + description = ["Option with optional parameters"]) + lateinit var values: List<String> +}
Kotlin
-
@Option(names = ["--syslog"], defaultValue = "OFF", fallbackValue = "INFO",
-    description = [
-        "When specified without arguments, start sending syslog messages at INFO level.",
-        "If absent, no messages are sent to syslog.",
-        "Optionally specify a severity value. Valid values: \${COMPLETION-CANDIDATES}."])
-lateinit var syslogLevel: MyLogLevel
+
@Option(names = ["--syslog"], defaultValue = "OFF", fallbackValue = "INFO",
+    description = [
+        "When specified without arguments, start sending syslog messages at INFO level.",
+        "If absent, no messages are sent to syslog.",
+        "Optionally specify a severity value. Valid values: \${COMPLETION-CANDIDATES}."])
+lateinit var syslogLevel: MyLogLevel
Kotlin
-
class Ambiguous {
-    @Parameters(description = ["The file (required)."])
-    lateinit var file: File
+
class Ambiguous {
+    @Parameters(description = ["The file (required)."])
+    lateinit var file: File
 
-    @Option(names = ["-x"], arity = "0..1",
-        description = ["Option with optional parameter"])
-    lateinit var value: String
-}
+ @Option(names = ["-x"], arity = "0..1", + description = ["Option with optional parameter"]) + lateinit var value: String +}
@@ -5273,25 +4982,25 @@

7.1.
Java
-
class MandatoryOption {
-    @Option(names = "-n", required = true, description = "mandatory number")
-    int number;
+
class MandatoryOption {
+    @Option(names = "-n", required = true, description = "mandatory number")
+    int number;
 
-    @Parameters
-    File[] files;
-}
+ @Parameters + File[] files; +}
Kotlin
-
class MandatoryOption {
-    @Option(names = ["-n"], required = true, description = ["mandatory number"])
-    var number = 0
+
class MandatoryOption {
+    @Option(names = ["-n"], required = true, description = ["mandatory number"])
+    var number = 0
 
-    @Parameters
-    lateinit var files: Array<File>
-}
+ @Parameters + lateinit var files: Array<File> +}
@@ -5324,25 +5033,25 @@

Java
-
class BothOptionAndParametersMandatory {
-    @Parameters(arity = "1..*", description = "at least one File")
-    File[] files;
+
class BothOptionAndParametersMandatory {
+    @Parameters(arity = "1..*", description = "at least one File")
+    File[] files;
 
-    @Option(names = "-n", required = true, description = "mandatory number")
-    int number;
-}
+ @Option(names = "-n", required = true, description = "mandatory number") + int number; +}

Kotlin
-
class BothOptionAndParametersMandatory {
-    @Parameters(arity = "1..*", description = ["at least one File"])
-    lateinit var files: Array<File>
+
class BothOptionAndParametersMandatory {
+    @Parameters(arity = "1..*", description = ["at least one File"])
+    lateinit var files: Array<File>
 
-    @Option(names = ["-n"], required = true, description = ["mandatory number"])
-    var number = 0
-}
+ @Option(names = ["-n"], required = true, description = ["mandatory number"]) + var number = 0 +}
Kotlin
-
@Command(name = "exclusivedemo")
-class MutuallyExclusiveOptionsDemo {
+
@Command(name = "exclusivedemo")
+class MutuallyExclusiveOptionsDemo {
 
-    @ArgGroup(exclusive = true, multiplicity = "1")
-    lateinit var exclusive: Exclusive
+    @ArgGroup(exclusive = true, multiplicity = "1")
+    lateinit var exclusive: Exclusive
 
-    class Exclusive {
-        @Option(names = ["-a"], required = true) var a = 0
-        @Option(names = ["-b"], required = true) var b = 0
-        @Option(names = ["-c"], required = true) var c = 0
-    }
-}
+ class Exclusive { + @Option(names = ["-a"], required = true) var a = 0 + @Option(names = ["-b"], required = true) var b = 0 + @Option(names = ["-c"], required = true) var c = 0 + } +}
Kotlin
-
val example = MutuallyExclusiveOptionsDemo()
-val cmd = CommandLine(example)
+
val example = MutuallyExclusiveOptionsDemo()
+val cmd = CommandLine(example)
 
-try {
-    cmd.parseArgs("-a=1", "-b=2")
-} catch (ex: MutuallyExclusiveArgsException) {
-    assert("Error: -a=<a>, -b=<b> are mutually exclusive (specify only one)" == ex.message)
-}
+try { + cmd.parseArgs("-a=1", "-b=2") +} catch (ex: MutuallyExclusiveArgsException) { + assert("Error: -a=<a>, -b=<b> are mutually exclusive (specify only one)" == ex.message) +}
@@ -5550,35 +5259,35 @@

8.2.1. Overview
Java
-
@Command(name = "co-occur")
-public class DependentOptionsDemo {
+
@Command(name = "co-occur")
+public class DependentOptionsDemo {
 
-    @ArgGroup(exclusive = false)
-    Dependent dependent;
+    @ArgGroup(exclusive = false)
+    Dependent dependent;
 
-    static class Dependent {
-        @Option(names = "-a", required = true) int a;
-        @Option(names = "-b", required = true) int b;
-        @Option(names = "-c", required = true) int c;
-    }
-}
+ static class Dependent { + @Option(names = "-a", required = true) int a; + @Option(names = "-b", required = true) int b; + @Option(names = "-c", required = true) int c; + } +}

Kotlin
-
@Command(name = "co-occur")
-class DependentOptionsDemo {
+
@Command(name = "co-occur")
+class DependentOptionsDemo {
 
-    @ArgGroup(exclusive = false)
-    lateinit var dependent: Dependent
+    @ArgGroup(exclusive = false)
+    lateinit var dependent: Dependent
 
-    class Dependent {
-        @Option(names = ["-a"], required = true) var a = 0
-        @Option(names = ["-b"], required = true) var b = 0
-        @Option(names = ["-c"], required = true) var c = 0
-    }
-}
+ class Dependent { + @Option(names = ["-a"], required = true) var a = 0 + @Option(names = ["-b"], required = true) var b = 0 + @Option(names = ["-c"], required = true) var c = 0 + } +}
@@ -5608,27 +5317,27 @@

8.2.1. Overview
Java
-
DependentOptionsDemo example = new DependentOptionsDemo();
-CommandLine cmd = new CommandLine(example);
+
DependentOptionsDemo example = new DependentOptionsDemo();
+CommandLine cmd = new CommandLine(example);
 
-try {
-    cmd.parseArgs("-a=1", "-b=2");
-} catch (MissingParameterException ex) {
-    assert "Error: Missing required argument(s): -c=<c>".equals(ex.getMessage());
-}
+try { + cmd.parseArgs("-a=1", "-b=2"); +} catch (MissingParameterException ex) { + assert "Error: Missing required argument(s): -c=<c>".equals(ex.getMessage()); +}

Kotlin
-
val example = DependentOptionsDemo()
-val cmd = CommandLine(example)
+
val example = DependentOptionsDemo()
+val cmd = CommandLine(example)
 
-try {
-    cmd.parseArgs("-a=1", "-b=2")
-} catch (ex: MissingParameterException) {
-    assert("Error: Missing required argument(s): -c=<c>" == ex.message)
-}
+try { + cmd.parseArgs("-a=1", "-b=2") +} catch (ex: MissingParameterException) { + assert("Error: Missing required argument(s): -c=<c>" == ex.message) +}
Kotlin
-
@Command(name = "co-occur-with-optional-options")
-class DependentWithOptionalOptionsDemo {
+
@Command(name = "co-occur-with-optional-options")
+class DependentWithOptionalOptionsDemo {
 
-    @ArgGroup(exclusive = false, multiplicity = "1")
-    lateinit var group: DependentWithOptionalOptions
+    @ArgGroup(exclusive = false, multiplicity = "1")
+    lateinit var group: DependentWithOptionalOptions
 
-    class DependentWithOptionalOptions {
-        @Option(names = ["-a"], required = true)  var a = 0
-        @Option(names = ["-b"], required = true)  var b = 0
-        @Option(names = ["-c"], required = false) var c = 0
-    }
-}
+ class DependentWithOptionalOptions { + @Option(names = ["-a"], required = true) var a = 0 + @Option(names = ["-b"], required = true) var b = 0 + @Option(names = ["-c"], required = false) var c = 0 + } +}
@@ -5712,61 +5421,61 @@

Java
-
@Command(name = "sectiondemo", description = "Section demo")
-public class OptionSectionDemo {
+
@Command(name = "sectiondemo", description = "Section demo")
+public class OptionSectionDemo {
 
-    @ArgGroup(validate = false, heading = "This is the first section%n")
-    Section1 section1;
+    @ArgGroup(validate = false, heading = "This is the first section%n")
+    Section1 section1;
 
-    static class Section1 {
-        @Option(names = "-a", description = "Option A") int a;
-        @Option(names = "-b", description = "Option B") int b;
-        @Option(names = "-c", description = "Option C") int c;
-    }
+    static class Section1 {
+        @Option(names = "-a", description = "Option A") int a;
+        @Option(names = "-b", description = "Option B") int b;
+        @Option(names = "-c", description = "Option C") int c;
+    }
 
-    @ArgGroup(validate = false, heading = "This is the second section%n")
-    Section2 section2;
+    @ArgGroup(validate = false, heading = "This is the second section%n")
+    Section2 section2;
 
-    static class Section2 {
-        @Option(names = "-x", description = "Option X") int x;
-        @Option(names = "-y", description = "Option Y") int y;
-        @Option(names = "-z", description = "Option Z") int z;
-    }
+    static class Section2 {
+        @Option(names = "-x", description = "Option X") int x;
+        @Option(names = "-y", description = "Option Y") int y;
+        @Option(names = "-z", description = "Option Z") int z;
+    }
 
-    public static void main(String[] args) {
-        new CommandLine(new OptionSectionDemo()).usage(System.out);
-    }
-}
+ public static void main(String[] args) { + new CommandLine(new OptionSectionDemo()).usage(System.out); + } +}

Kotlin
-
@Command(name = "sectiondemo", description = ["Section demo"])
-class OptionSectionDemo {
+
@Command(name = "sectiondemo", description = ["Section demo"])
+class OptionSectionDemo {
 
-    @ArgGroup(validate = false, heading = "This is the first section%n")
-    lateinit var section1: Section1
+    @ArgGroup(validate = false, heading = "This is the first section%n")
+    lateinit var section1: Section1
 
-    class Section1 {
-        @Option(names = ["-a"], description = ["Option A"]) var a = 0
-        @Option(names = ["-b"], description = ["Option B"]) var b = 0
-        @Option(names = ["-c"], description = ["Option C"]) var c = 0
-    }
+    class Section1 {
+        @Option(names = ["-a"], description = ["Option A"]) var a = 0
+        @Option(names = ["-b"], description = ["Option B"]) var b = 0
+        @Option(names = ["-c"], description = ["Option C"]) var c = 0
+    }
 
-    @ArgGroup(validate = false, heading = "This is the second section%n")
-    lateinit var section2: Section2
+    @ArgGroup(validate = false, heading = "This is the second section%n")
+    lateinit var section2: Section2
 
-    class Section2 {
-        @Option(names = ["-x"], description = ["Option X"]) var x = 0
-        @Option(names = ["-y"], description = ["Option Y"]) var y = 0
-        @Option(names = ["-z"], description = ["Option Z"]) var z = 0
-    }
-}
+    class Section2 {
+        @Option(names = ["-x"], description = ["Option X"]) var x = 0
+        @Option(names = ["-y"], description = ["Option Y"]) var y = 0
+        @Option(names = ["-z"], description = ["Option Z"]) var z = 0
+    }
+}
 
-fun main(args: Array<String>) {
-    CommandLine(OptionSectionDemo()).usage(System.out)
-}
+fun main(args: Array<String>) { + CommandLine(OptionSectionDemo()).usage(System.out) +}
@@ -5839,61 +5548,61 @@

Java
-
@Command(name = "repeating-composite-demo")
-public class CompositeGroupDemo {
+
@Command(name = "repeating-composite-demo")
+public class CompositeGroupDemo {
 
-    @ArgGroup(exclusive = false, multiplicity = "1..*")
-    List<Composite> composites;
+    @ArgGroup(exclusive = false, multiplicity = "1..*")
+    List<Composite> composites;
 
-    static class Composite {
-        @ArgGroup(exclusive = false, multiplicity = "0..1")
-        Dependent dependent;
+    static class Composite {
+        @ArgGroup(exclusive = false, multiplicity = "0..1")
+        Dependent dependent;
 
-        @ArgGroup(exclusive = true, multiplicity = "1")
-        Exclusive exclusive;
-    }
+        @ArgGroup(exclusive = true, multiplicity = "1")
+        Exclusive exclusive;
+    }
 
-    static class Dependent {
-        @Option(names = "-a", required = true) int a;
-        @Option(names = "-b", required = true) int b;
-        @Option(names = "-c", required = true) int c;
-    }
+    static class Dependent {
+        @Option(names = "-a", required = true) int a;
+        @Option(names = "-b", required = true) int b;
+        @Option(names = "-c", required = true) int c;
+    }
 
-    static class Exclusive {
-        @Option(names = "-x", required = true) boolean x;
-        @Option(names = "-y", required = true) boolean y;
-        @Option(names = "-z", required = true) boolean z;
-    }
-}
+ static class Exclusive { + @Option(names = "-x", required = true) boolean x; + @Option(names = "-y", required = true) boolean y; + @Option(names = "-z", required = true) boolean z; + } +}

Kotlin
-
@Command(name = "repeating-composite-demo")
-class CompositeGroupDemo {
-    @ArgGroup(exclusive = false, multiplicity = "1..*") lateinit var composites: List<Composite>
+
@Command(name = "repeating-composite-demo")
+class CompositeGroupDemo {
+    @ArgGroup(exclusive = false, multiplicity = "1..*") lateinit var composites: List<Composite>
 
-    class Composite {
-        @ArgGroup(exclusive = false, multiplicity = "0..1")
-        lateinit var dependent: Dependent
+    class Composite {
+        @ArgGroup(exclusive = false, multiplicity = "0..1")
+        lateinit var dependent: Dependent
 
-        @ArgGroup(exclusive = true, multiplicity = "1")
-        lateinit var exclusive: Exclusive
-    }
+        @ArgGroup(exclusive = true, multiplicity = "1")
+        lateinit var exclusive: Exclusive
+    }
 
-    class Dependent {
-        @Option(names = ["-a"], required = true) var a = 0
-        @Option(names = ["-b"], required = true) var b = 0
-        @Option(names = ["-c"], required = true) var c = 0
-    }
+    class Dependent {
+        @Option(names = ["-a"], required = true) var a = 0
+        @Option(names = ["-b"], required = true) var b = 0
+        @Option(names = ["-c"], required = true) var c = 0
+    }
 
-    class Exclusive {
-        @Option(names = ["-x"], required = true) var x = false
-        @Option(names = ["-y"], required = true) var y = false
-        @Option(names = ["-z"], required = true) var z = false
-    }
-}
+ class Exclusive { + @Option(names = ["-x"], required = true) var x = false + @Option(names = ["-y"], required = true) var y = false + @Option(names = ["-z"], required = true) var z = false + } +}
Kotlin
-
val example = CompositeGroupDemo()
-val cmd = CommandLine(example)
+
val example = CompositeGroupDemo()
+val cmd = CommandLine(example)
 
-cmd.parseArgs("-x", "-a=1", "-b=1", "-c=1", "-a=2", "-b=2", "-c=2", "-y")
-assert(example.composites.size == 2)
+cmd.parseArgs("-x", "-a=1", "-b=1", "-c=1", "-a=2", "-b=2", "-c=2", "-y")
+assert(example.composites.size == 2)
 
-val c1 = example.composites[0]
-assert(c1.exclusive.x)
-assert(c1.dependent.a === 1)
-assert(c1.dependent.b === 1)
-assert(c1.dependent.c === 1)
+val c1 = example.composites[0]
+assert(c1.exclusive.x)
+assert(c1.dependent.a === 1)
+assert(c1.dependent.b === 1)
+assert(c1.dependent.c === 1)
 
-val c2 = example.composites[1]
-assert(c2.exclusive.y)
-assert(c2.dependent.a === 2)
-assert(c2.dependent.b === 2)
-assert(c2.dependent.c === 2)
+val c2 = example.composites[1] +assert(c2.exclusive.y) +assert(c2.dependent.a === 2) +assert(c2.dependent.b === 2) +assert(c2.dependent.c === 2)
Kotlin
-
class GoodGroup {
-    @Option(names = ["-x"], defaultValue = "123", description = ["Default: \${DEFAULT-VALUE}"])
-    var x = 0
-}
+
class GoodGroup {
+    @Option(names = ["-x"], defaultValue = "123", description = ["Default: \${DEFAULT-VALUE}"])
+    var x = 0
+}
 
-@Command(name = "good", description = ["usage help shows the default value"])
-class GoodExample {
-    @ArgGroup
-    lateinit var goodGroup: GoodGroup
-}
+@Command(name = "good", description = ["usage help shows the default value"])
+class GoodExample {
+    @ArgGroup
+    lateinit var goodGroup: GoodGroup
+}
 
-fun main(args: Array<String>) {
-    CommandLine(GoodExample()).usage(System.out)
-}
+fun main(args: Array<String>) { + CommandLine(GoodExample()).usage(System.out) +}
Kotlin
-
class BadGroup {
-    @Option(names = ["-x"], description = ["Default: \${DEFAULT-VALUE}"])
-    var x = 123 // value not found until `BadGroup` is instantiated
-}
+
class BadGroup {
+    @Option(names = ["-x"], description = ["Default: \${DEFAULT-VALUE}"])
+    var x = 123 // value not found until `BadGroup` is instantiated
+}
 
-@Command(name = "bad", description = ["usage help shows wrong default value"])
-class BadExample {
-    @ArgGroup
-    lateinit var badGroup: BadGroup
-}
+@Command(name = "bad", description = ["usage help shows wrong default value"])
+class BadExample {
+    @ArgGroup
+    lateinit var badGroup: BadGroup
+}
 
-fun main(args: Array<String>) {
-    CommandLine(BadExample()).usage(System.out)
-}
+fun main(args: Array<String>) { + CommandLine(BadExample()).usage(System.out) +}
@@ -6103,74 +5812,122 @@

-

8.6. Positional Parameters

-
-

When a @Parameters positional parameter is part of a group, its index is the index within the group, not within the command.

-
+
+

8.5.2. Default Values in Unreferenced Argument Groups

-

Below is an example of an application that uses a repeating group of positional parameters:

+

When an argument group is defined with default values in the annotated fields, but during usage does not reference any of the arguments within the group, picocli will instantiate those objects to their declared values. However, picocli will instantiate the other objects to their default annotated values if a single argument within the argument group is defined.

Java
-
@Command(name = "grades", mixinStandardHelpOptions = true, version = "grades 1.0")
-public class Grades implements Runnable {
-
-    static class StudentGrade {
-        @Parameters(index = "0") String name;
-        @Parameters(index = "1") BigDecimal grade;
-    }
+
@Command(name = "test", description = "demonstrates Default Value declaration")
+class MyApp {
+    @ArgGroup Outer outer = new Outer();
 
-    @ArgGroup(exclusive = false, multiplicity = "1..*")
-    List<StudentGrade> gradeList;
-
-    @Override
-    public void run() {
-        gradeList.forEach(e -> System.out.println(e.name + ": " + e.grade));
-    }
+    class Outer {
+        @Options(names = "-x", defaultValue = "XX") String x;
+        @ArgGroup(exclusive = "true") Inner inner = new Inner();
+    }
 
-    public static void main(String[] args) {
-        System.exit(new CommandLine(new Grades()).execute(args));
-    }
-}
+ class Inner { + @Options(names = "-a", defaultValue = "AA") String a = "AA"; + @Options(names = "-b", defaultValue = "BB") String b = "BB"; + } +}
Kotlin
-
@Command(name = "grades", mixinStandardHelpOptions = true, version = ["grades 1.0"])
-class Grades : Runnable {
+
@Command(name = "test", description =["demonstrates Default Value declaration"])
+class MyApp {
+    @ArgGroup lateinit var outer: Outer
 
-    class StudentGrade {
-        @Parameters(index = "0") lateinit var name: String
-        @Parameters(index = "1") lateinit var grade: BigDecimal
-    }
-
-    @ArgGroup(exclusive = false, multiplicity = "1..*")
-    lateinit var gradeList: List<StudentGrade>
+    class Outer {
+        @Options(names = "-x", defaultValue = "XX") lateinit var x: String()
+        @ArgGroup lateinit var inner: Inner
+    }
 
-    override fun run() {
-        gradeList.forEach { e -> println("${e.name}: ${e.grade}") }
-    }
-}
+    class Inner {
+        @Options(names = "-a", defaultValue = "AA") var a = "AA"
+        @Options(names = "-b", defaultValue = "BB") var b = "BB"
+    }
 
-fun main(args: Array<String>) {
-    System.exit(CommandLine(Grades()).execute(*args))
-}
+}
-

Running the above program with this input:

+

In this example above, there are two cases why we need to write our class with both annotated and declared values. The first reason is that if we do not supply any arguments, the annotated "defaultValues" field will provide the instantiated value. The second reason is if we provide an "x" value but no "a" or "b" value, the variables use their declared value instead of the annotated value. Thus, in our example, by setting the annotated "defaultValue" and the declared value to the same default value, we ensure that we always have the correct default value for different combinations of arguments.

-
-
-
Alice 3.1 Betty 4.0 "X Æ A-12" 3.5 Zaphod 3.4
+
+

8.6. Positional Parameters

-

Produces the following output:

+

When a @Parameters positional parameter is part of a group, its index is the index within the group, not within the command.

+
+
+

Below is an example of an application that uses a repeating group of positional parameters:

+
+
+
Java
+
+
@Command(name = "grades", mixinStandardHelpOptions = true, version = "grades 1.0")
+public class Grades implements Runnable {
+
+    static class StudentGrade {
+        @Parameters(index = "0") String name;
+        @Parameters(index = "1") BigDecimal grade;
+    }
+
+    @ArgGroup(exclusive = false, multiplicity = "1..*")
+    List<StudentGrade> gradeList;
+
+    @Override
+    public void run() {
+        gradeList.forEach(e -> System.out.println(e.name + ": " + e.grade));
+    }
+
+    public static void main(String[] args) {
+        System.exit(new CommandLine(new Grades()).execute(args));
+    }
+}
+
+
+
+
Kotlin
+
+
@Command(name = "grades", mixinStandardHelpOptions = true, version = ["grades 1.0"])
+class Grades : Runnable {
+
+    class StudentGrade {
+        @Parameters(index = "0") lateinit var name: String
+        @Parameters(index = "1") lateinit var grade: BigDecimal
+    }
+
+    @ArgGroup(exclusive = false, multiplicity = "1..*")
+    lateinit var gradeList: List<StudentGrade>
+
+    override fun run() {
+        gradeList.forEach { e -> println("${e.name}: ${e.grade}") }
+    }
+}
+
+fun main(args: Array<String>) {
+    System.exit(CommandLine(Grades()).execute(*args))
+}
+
+
+
+

Running the above program with this input:

+
+
+
+
Alice 3.1 Betty 4.0 "X Æ A-12" 3.5 Zaphod 3.4
+
+
+
+

Produces the following output:

@@ -6236,13 +5993,13 @@

9. Executing Commands

Java
-
new CommandLine(new MyApp()).execute(args);
+
new CommandLine(new MyApp()).execute(args);
Kotlin
-
CommandLine(MyApp()).execute(*args)
+
CommandLine(MyApp()).execute(*args)
@@ -6251,73 +6008,41 @@

9. Executing Commands

Java
-
 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
-10
-11
-12
-13
-14
-15
-
@Command(name = "myapp", mixinStandardHelpOptions = true, version = "1.0")
-class MyApp implements Callable<Integer> {
-
-    @Option(names = "-x") int x;
-
-    @Override
-    public Integer call() { // business logic
-        System.out.printf("x=%s%n", x);
-        return 123; // exit code
-    }
-
-    public static void main(String... args) { // bootstrap the application
-        System.exit(new CommandLine(new MyApp()).execute(args));
-    }
-}
-
+
@Command(name = "myapp", mixinStandardHelpOptions = true, version = "1.0")
+class MyApp implements Callable<Integer> {
+
+    @Option(names = "-x") int x;
+
+    @Override
+    public Integer call() { // business logic
+        System.out.printf("x=%s%n", x);
+        return 123; // exit code
+    }
+
+    public static void main(String... args) { // bootstrap the application
+        System.exit(new CommandLine(new MyApp()).execute(args));
+    }
+}
Kotlin
-
 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
-10
-11
-12
-13
-14
-15
-
@Command(name = "myapp", mixinStandardHelpOptions = true, version = ["1.0"])
-class MyApp : Callable<Int> {
-
-    @Option(names = ["-x"])
-    var x = 0
-
-    override fun call(): Int { // business logic
-        println("x=$x")
-        return 123 // exit code
-    }
-}
-
-fun main(args: Array<String>) { // bootstrap the application
-    exitProcess(CommandLine(MyApp()).execute(*args))
-}
-
+
@Command(name = "myapp", mixinStandardHelpOptions = true, version = ["1.0"])
+class MyApp : Callable<Int> {
+
+    @Option(names = ["-x"])
+    var x = 0
+
+    override fun call(): Int { // business logic
+        println("x=$x")
+        return 123 // exit code
+    }
+}
+
+fun main(args: Array<String>) { // bootstrap the application
+    exitProcess(CommandLine(MyApp()).execute(*args))
+}
@@ -6364,19 +6089,19 @@

9.1. Exit Code

Java
-
public static void main(String... args) {
-  int exitCode = new CommandLine(new MyApp()).execute(args);
-  System.exit(exitCode);
-}
+
public static void main(String... args) {
+  int exitCode = new CommandLine(new MyApp()).execute(args);
+  System.exit(exitCode);
+}
Kotlin
-
fun main(args: Array<String>) {
-    val exitCode = CommandLine(MyApp()).execute(*args)
-    exitProcess(exitCode)
-}
+
fun main(args: Array<String>) {
+    val exitCode = CommandLine(MyApp()).execute(*args)
+    exitProcess(exitCode)
+}
Kotlin
-
@Command(name = "greet")
-class Greet : Callable<Int> {
-    override fun call(): Int {
-        println("hi")
-        return 1
-    }
+
@Command(name = "greet")
+class Greet : Callable<Int> {
+    override fun call(): Int {
+        println("hi")
+        return 1
+    }
 
-    // define a "shout" subcommand with a @Command-annotated method
-    @Command
-    fun shout(): Int {
-        println("HI!")
-        return 2
-    }
-}
+    // define a "shout" subcommand with a @Command-annotated method
+    @Command
+    fun shout(): Int {
+        println("HI!")
+        return 2
+    }
+}
 
-assert(1 == CommandLine(Greet()).execute())
-assert(2 == CommandLine(Greet()).execute("shout"))
+assert(1 == CommandLine(Greet()).execute()) +assert(2 == CommandLine(Greet()).execute("shout"))
Kotlin
-
@Command(name = "wave")
-class Gesture : Runnable, IExitCodeGenerator {
+
@Command(name = "wave")
+class Gesture : Runnable, IExitCodeGenerator {
 
-    override fun run() {
-        println("wave")
-    }
+    override fun run() {
+        println("wave")
+    }
 
-    override fun getExitCode(): Int {
-        return 3
-    }
-}
+    override fun getExitCode(): Int {
+        return 3
+    }
+}
 
-assert(3 == CommandLine(Gesture()).execute())
+assert(3 == CommandLine(Gesture()).execute())
@@ -6488,8 +6213,8 @@

<

-
@Command(exitCodeOnInvalidInput = 123,
-   exitCodeOnExecutionException = 456)
+
@Command(exitCodeOnInvalidInput = 123,
+   exitCodeOnExecutionException = 456)
@@ -6498,27 +6223,27 @@

<
Java
-
class MyMapper implements IExitCodeExceptionMapper {
-    @Override
-    public int getExitCode(Throwable t) {
-        if (t instanceof FileNotFoundException) {
-            return 74;
-        }
-        return 1;
-    }
-}
+
class MyMapper implements IExitCodeExceptionMapper {
+    @Override
+    public int getExitCode(Throwable t) {
+        if (t instanceof FileNotFoundException) {
+            return 74;
+        }
+        return 1;
+    }
+}
Kotlin
-
class MyMapper : IExitCodeExceptionMapper {
-    override fun getExitCode(t: Throwable): Int {
-        return if (t is FileNotFoundException) {
-            74
-        } else 1
-    }
-}
+
class MyMapper : IExitCodeExceptionMapper {
+    override fun getExitCode(t: Throwable): Int {
+        return if (t is FileNotFoundException) {
+            74
+        } else 1
+    }
+}
Kotlin
-
val out: PrintStream = // output stream for user-requested help
-val err: PrintStream = // output stream for error messages
-val ansi: Ansi = // to use ANSI colors and styles or not
-CommandLine.run(MyRunnable(), out, err, ansi, *args)
+
val out: PrintStream = // output stream for user-requested help
+val err: PrintStream = // output stream for error messages
+val ansi: Ansi = // to use ANSI colors and styles or not
+CommandLine.run(MyRunnable(), out, err, ansi, *args)
Kotlin
-
var out: PrintWriter = // output stream for user-requested help
-var err: PrintWriter = // output stream for error messages
-val ansi: Ansi = // to use ANSI colors and styles or not
+
var out: PrintWriter = // output stream for user-requested help
+var err: PrintWriter = // output stream for error messages
+val ansi: Ansi = // to use ANSI colors and styles or not
 
-val cmd = CommandLine(MyRunnable())
-        .setOut(out)
-        .setErr(err)
-        .setColorScheme(Help.defaultColorScheme(ansi));
+val cmd = CommandLine(MyRunnable())
+        .setOut(out)
+        .setErr(err)
+        .setColorScheme(Help.defaultColorScheme(ansi));
 
-val exitCode = cmd.execute(*args)
+val exitCode = cmd.execute(*args)

@@ -6655,21 +6380,21 @@

Java
-
class MyCallable implements Callable<MyResult> {
-    public MyResult call() { /* ... */ }
-}
+
class MyCallable implements Callable<MyResult> {
+    public MyResult call() { /* ... */ }
+}
 
-MyResult result = CommandLine.call(new MyCallable(), args);
+MyResult result = CommandLine.call(new MyCallable(), args);

Kotlin
-
class MyCallable : Callable<MyResult> {
-    override fun call(): MyResult { /* ... */ }
-}
+
class MyCallable : Callable<MyResult> {
+    override fun call(): MyResult { /* ... */ }
+}
 
-val result: MyResult = CommandLine.call(MyCallable(), *args)
+val result: MyResult = CommandLine.call(MyCallable(), *args)
Kotlin
-
val cmd = CommandLine(MyCallable())
-val exitCode = cmd.execute(*args)
-val result: MyResult = cmd.getExecutionResult()
+
val cmd = CommandLine(MyCallable())
+val exitCode = cmd.execute(*args)
+val result: MyResult = cmd.getExecutionResult()
@@ -6700,23 +6425,23 @@

Java
-
class MyCommand {
-    @Command
-    public MyResult doit(@Option(names = "-x") int x) { ... }
-}
+
class MyCommand {
+    @Command
+    public MyResult doit(@Option(names = "-x") int x) { ... }
+}
 
-MyResult result = CommandLine.invoke("doit", MyCommand.class, args);
+MyResult result = CommandLine.invoke("doit", MyCommand.class, args);

Kotlin
-
class MyCommand {
-    @Command
-    fun doit(@Option(names = ["-x"]) x: Int) : MyResult{ /* ... */ }
-}
+
class MyCommand {
+    @Command
+    fun doit(@Option(names = ["-x"]) x: Int) : MyResult{ /* ... */ }
+}
 
-val result = CommandLine.invoke("doit", MyCommand::class.java, *args) as MyResult
+val result = CommandLine.invoke("doit", MyCommand::class.java, *args) as MyResult
Kotlin
-
val doit: Method = CommandLine.getCommandMethods(MyCommand::class.java, "doit")[0]
-val cmd = CommandLine(doit)
-val exitCode = cmd.execute(*args)
-val result: MyResult = cmd.getExecutionResult()
+
val doit: Method = CommandLine.getCommandMethods(MyCommand::class.java, "doit")[0]
+val cmd = CommandLine(doit)
+val exitCode = cmd.execute(*args)
+val result: MyResult = cmd.getExecutionResult()
@@ -6765,21 +6490,21 @@

Java
-
CommandLine cmd = new CommandLine(MyTopLevelCommand())
-        .addSubcommand("status",   new GitStatus())
-        .addSubcommand("commit",   new GitCommit())
-        .addSubcommand("add",      new GitAdd());
-List<Object> result = cmd.parseWithHandler(new RunAll(), args);
+
CommandLine cmd = new CommandLine(MyTopLevelCommand())
+        .addSubcommand("status",   new GitStatus())
+        .addSubcommand("commit",   new GitCommit())
+        .addSubcommand("add",      new GitAdd());
+List<Object> result = cmd.parseWithHandler(new RunAll(), args);

Kotlin
-
val cmd = CommandLine(MyTopLevelCommand())
-        .addSubcommand("status",   GitStatus())
-        .addSubcommand("commit",   GitCommit())
-        .addSubcommand("add",      GitAdd())
-val result = cmd.parseWithHandler<List<Any>>(CommandLine.RunAll(), args)}
+
val cmd = CommandLine(MyTopLevelCommand())
+        .addSubcommand("status",   GitStatus())
+        .addSubcommand("commit",   GitCommit())
+        .addSubcommand("add",      GitAdd())
+val result = cmd.parseWithHandler<List<Any>>(CommandLine.RunAll(), args)}
Kotlin
-
val cmd = CommandLine(MyTopLevelCommand())
-        .addSubcommand("status",   GitStatus())
-        .addSubcommand("commit",   GitCommit())
-        .addSubcommand("add",      GitAdd())
+
val cmd = CommandLine(MyTopLevelCommand())
+        .addSubcommand("status",   GitStatus())
+        .addSubcommand("commit",   GitCommit())
+        .addSubcommand("add",      GitAdd())
 
-// the default is RunLast, this can be customized:
-cmd.executionStrategy = RunAll()
-val exitCode = cmd.execute(*args)
+// the default is RunLast, this can be customized: +cmd.executionStrategy = RunAll() +val exitCode = cmd.execute(*args)
Kotlin
-
// getting return value from Callable or Method command
-val topResult: Int = cmd.getExecutionResult()
+
// getting return value from Callable or Method command
+val topResult: Int = cmd.getExecutionResult()
 
-// getting return value from Callable or Method subcommand
-val parseResult = cmd.parseResult
-if (parseResult.subcommand() != null) {
-    val sub: CommandLine = parseResult.subcommand().commandSpec().commandLine()
-    val subResult = sub.getExecutionResult<Int>()
-}
+// getting return value from Callable or Method subcommand +val parseResult = cmd.parseResult +if (parseResult.subcommand() != null) { + val sub: CommandLine = parseResult.subcommand().commandSpec().commandLine() + val subResult = sub.getExecutionResult<Int>() +}

@@ -6874,77 +6599,77 @@

Java
-
Callable<Object> callable = new MyCallable();
-CommandLine cmd = new CommandLine(callable);
-try {
-    ParseResult parseResult = cmd.parseArgs(args);
-
-    // Did user request usage help (--help)?
-    if (cmd.isUsageHelpRequested()) {
-        cmd.usage(cmd.getOut());
-        return cmd.getCommandSpec().exitCodeOnUsageHelp();
-
-    // Did user request version help (--version)?
-    } else if (cmd.isVersionHelpRequested()) {
-        cmd.printVersionHelp(cmd.getOut());
-        return cmd.getCommandSpec().exitCodeOnVersionHelp();
-    }
-    // invoke the business logic
-    Object result = callable.call();
-    cmd.setExecutionResult(result);
-    return cmd.getCommandSpec().exitCodeOnSuccess();
-
-// invalid user input: print error message and usage help
-} catch (ParameterException ex) {
-    cmd.getErr().println(ex.getMessage());
-    if (!UnmatchedArgumentException.printSuggestions(ex, cmd.getErr())) {
-        ex.getCommandLine().usage(cmd.getErr());
-    }
-    return cmd.getCommandSpec().exitCodeOnInvalidInput();
-
-// exception occurred in business logic
-} catch (Exception ex) {
-    ex.printStackTrace(cmd.getErr());
-    return cmd.getCommandSpec().exitCodeOnExecutionException();
-}
+
Callable<Object> callable = new MyCallable();
+CommandLine cmd = new CommandLine(callable);
+try {
+    ParseResult parseResult = cmd.parseArgs(args);
+
+    // Did user request usage help (--help)?
+    if (cmd.isUsageHelpRequested()) {
+        cmd.usage(cmd.getOut());
+        return cmd.getCommandSpec().exitCodeOnUsageHelp();
+
+    // Did user request version help (--version)?
+    } else if (cmd.isVersionHelpRequested()) {
+        cmd.printVersionHelp(cmd.getOut());
+        return cmd.getCommandSpec().exitCodeOnVersionHelp();
+    }
+    // invoke the business logic
+    Object result = callable.call();
+    cmd.setExecutionResult(result);
+    return cmd.getCommandSpec().exitCodeOnSuccess();
+
+// invalid user input: print error message and usage help
+} catch (ParameterException ex) {
+    cmd.getErr().println(ex.getMessage());
+    if (!UnmatchedArgumentException.printSuggestions(ex, cmd.getErr())) {
+        ex.getCommandLine().usage(cmd.getErr());
+    }
+    return cmd.getCommandSpec().exitCodeOnInvalidInput();
+
+// exception occurred in business logic
+} catch (Exception ex) {
+    ex.printStackTrace(cmd.getErr());
+    return cmd.getCommandSpec().exitCodeOnExecutionException();
+}

Kotlin
-
val callable: Callable<Int> = MyCallable()
-val cmd = CommandLine(callable)
-return try {
-    val parseResult = cmd.parseArgs(*args)
-
-    // Did user request usage help (--help)?
-    if (cmd.isUsageHelpRequested) {
-        cmd.usage(cmd.out)
-        cmd.commandSpec.exitCodeOnUsageHelp()
-
-        // Did user request version help (--version)?
-    } else if (cmd.isVersionHelpRequested) {
-        cmd.printVersionHelp(cmd.out)
-        return cmd.commandSpec.exitCodeOnVersionHelp()
-    }
-    // invoke the business logic
-    val result = callable.call()
-    cmd.setExecutionResult(result)
-    cmd.commandSpec.exitCodeOnSuccess()
-
-    // invalid user input: print error message and usage help
-} catch (ex: ParameterException) {
-    cmd.err.println(ex.message)
-    if (!UnmatchedArgumentException.printSuggestions(ex, cmd.err)) {
-        ex.commandLine.usage(cmd.err)
-    }
-    cmd.commandSpec.exitCodeOnInvalidInput()
-
-    // exception occurred in business logic
-} catch (ex: Exception) {
-    ex.printStackTrace(cmd.err)
-    cmd.commandSpec.exitCodeOnExecutionException()
-}
+
val callable: Callable<Int> = MyCallable()
+val cmd = CommandLine(callable)
+return try {
+    val parseResult = cmd.parseArgs(*args)
+
+    // Did user request usage help (--help)?
+    if (cmd.isUsageHelpRequested) {
+        cmd.usage(cmd.out)
+        cmd.commandSpec.exitCodeOnUsageHelp()
+
+        // Did user request version help (--version)?
+    } else if (cmd.isVersionHelpRequested) {
+        cmd.printVersionHelp(cmd.out)
+        return cmd.commandSpec.exitCodeOnVersionHelp()
+    }
+    // invoke the business logic
+    val result = callable.call()
+    cmd.setExecutionResult(result)
+    cmd.commandSpec.exitCodeOnSuccess()
+
+    // invalid user input: print error message and usage help
+} catch (ex: ParameterException) {
+    cmd.err.println(ex.message)
+    if (!UnmatchedArgumentException.printSuggestions(ex, cmd.err)) {
+        ex.commandLine.usage(cmd.err)
+    }
+    cmd.commandSpec.exitCodeOnInvalidInput()
+
+    // exception occurred in business logic
+} catch (ex: Exception) {
+    ex.printStackTrace(cmd.err)
+    cmd.commandSpec.exitCodeOnExecutionException()
+}
@@ -6999,17 +6724,17 @@

9
Java
-
new CommandLine(new MyApp())
-    .setParameterExceptionHandler(new ShortErrorMessageHandler())
-    .execute(args);
+
new CommandLine(new MyApp())
+    .setParameterExceptionHandler(new ShortErrorMessageHandler())
+    .execute(args);
Kotlin
-
CommandLine(MyApp())
-    .setParameterExceptionHandler(ShortErrorMessageHandler())
-    .execute(*args)
+
CommandLine(MyApp())
+    .setParameterExceptionHandler(ShortErrorMessageHandler())
+    .execute(*args)
@@ -7018,57 +6743,57 @@

9
Java
-
class ShortErrorMessageHandler implements IParameterExceptionHandler {
+
class ShortErrorMessageHandler implements IParameterExceptionHandler {
 
-    public int handleParseException(ParameterException ex, String[] args) {
-        CommandLine cmd = ex.getCommandLine();
-        PrintWriter err = cmd.getErr();
+    public int handleParseException(ParameterException ex, String[] args) {
+        CommandLine cmd = ex.getCommandLine();
+        PrintWriter err = cmd.getErr();
 
-        // if tracing at DEBUG level, show the location of the issue
-        if ("DEBUG".equalsIgnoreCase(System.getProperty("picocli.trace"))) {
-            err.println(cmd.getColorScheme().stackTraceText(ex));
-        }
+        // if tracing at DEBUG level, show the location of the issue
+        if ("DEBUG".equalsIgnoreCase(System.getProperty("picocli.trace"))) {
+            err.println(cmd.getColorScheme().stackTraceText(ex));
+        }
 
-        err.println(cmd.getColorScheme().errorText(ex.getMessage())); // bold red
-        UnmatchedArgumentException.printSuggestions(ex, err);
-        err.print(cmd.getHelp().fullSynopsis());
+        err.println(cmd.getColorScheme().errorText(ex.getMessage())); // bold red
+        UnmatchedArgumentException.printSuggestions(ex, err);
+        err.print(cmd.getHelp().fullSynopsis());
 
-        CommandSpec spec = cmd.getCommandSpec();
-        err.printf("Try '%s --help' for more information.%n", spec.qualifiedName());
+        CommandSpec spec = cmd.getCommandSpec();
+        err.printf("Try '%s --help' for more information.%n", spec.qualifiedName());
 
-        return cmd.getExitCodeExceptionMapper() != null
-                    ? cmd.getExitCodeExceptionMapper().getExitCode(ex)
-                    : spec.exitCodeOnInvalidInput();
-    }
-}
+ return cmd.getExitCodeExceptionMapper() != null + ? cmd.getExitCodeExceptionMapper().getExitCode(ex) + : spec.exitCodeOnInvalidInput(); + } +}
Kotlin
-
class ShortErrorMessageHandler : IParameterExceptionHandler {
+
class ShortErrorMessageHandler : IParameterExceptionHandler {
 
-    override fun handleParseException(ex: ParameterException, args: Array<String>): Int {
-        val cmd = ex.commandLine
-        val err = cmd.err
+    override fun handleParseException(ex: ParameterException, args: Array<String>): Int {
+        val cmd = ex.commandLine
+        val err = cmd.err
 
-        // if tracing at DEBUG level, show the location of the issue
-        if ("DEBUG".equals(System.getProperty("picocli.trace"), ignoreCase = true)) {
-            err.println(cmd.colorScheme.stackTraceText(ex))
-        }
+        // if tracing at DEBUG level, show the location of the issue
+        if ("DEBUG".equals(System.getProperty("picocli.trace"), ignoreCase = true)) {
+            err.println(cmd.colorScheme.stackTraceText(ex))
+        }
 
-        err.println(cmd.colorScheme.errorText(ex.message)) // bold red
-        UnmatchedArgumentException.printSuggestions(ex, err)
-        err.print(cmd.help.fullSynopsis())
+        err.println(cmd.colorScheme.errorText(ex.message)) // bold red
+        UnmatchedArgumentException.printSuggestions(ex, err)
+        err.print(cmd.help.fullSynopsis())
 
-        val spec = cmd.commandSpec
-        err.print("Try '${spec.qualifiedName()} --help' for more information.%n")
+        val spec = cmd.commandSpec
+        err.print("Try '${spec.qualifiedName()} --help' for more information.%n")
 
-        return if (cmd.exitCodeExceptionMapper != null)
-            cmd.exitCodeExceptionMapper.getExitCode(ex)
-            else spec.exitCodeOnInvalidInput()
-    }
-}
+ return if (cmd.exitCodeExceptionMapper != null) + cmd.exitCodeExceptionMapper.getExitCode(ex) + else spec.exitCodeOnInvalidInput() + } +}

@@ -7088,17 +6813,17 @@

Java
-
new CommandLine(new MyApp())
-    .setExecutionExceptionHandler(new PrintExceptionMessageHandler())
-    .execute(args);
+
new CommandLine(new MyApp())
+    .setExecutionExceptionHandler(new PrintExceptionMessageHandler())
+    .execute(args);

Kotlin
-
CommandLine(MyApp())
-    .setExecutionExceptionHandler(PrintExceptionMessageHandler())
-    .execute(*args)
+
CommandLine(MyApp())
+    .setExecutionExceptionHandler(PrintExceptionMessageHandler())
+    .execute(*args)
Kotlin
-
class PrintExceptionMessageHandler : IExecutionExceptionHandler {
-    override fun handleExecutionException(ex: Exception,
-                                          cmd: CommandLine,
-                                          parseResult: ParseResult): Int {
+
class PrintExceptionMessageHandler : IExecutionExceptionHandler {
+    override fun handleExecutionException(ex: Exception,
+                                          cmd: CommandLine,
+                                          parseResult: ParseResult): Int {
 
-        // bold red error message
-        cmd.err.println(cmd.colorScheme.errorText(ex.message))
+        // bold red error message
+        cmd.err.println(cmd.colorScheme.errorText(ex.message))
 
-        return if (cmd.exitCodeExceptionMapper != null)
-            cmd.exitCodeExceptionMapper.getExitCode(ex)
-            else cmd.commandSpec.exitCodeOnExecutionException()
-    }
-}
+ return if (cmd.exitCodeExceptionMapper != null) + cmd.exitCodeExceptionMapper.getExitCode(ex) + else cmd.commandSpec.exitCodeOnExecutionException() + } +}

@@ -7215,57 +6940,57 @@

Java
-
class SingleOptionValidationExample {
-    private int prime;
-
-    @Spec CommandSpec spec; // injected by picocli
-
-    @Option(names = {"-p", "--prime"}, paramLabel = "NUMBER")
-    public void setPrimeNumber(int value) {
-        boolean invalid = false;
-        for (int i = 2; i <= value / 2; i++) {
-            if (value % i == 0) {
-                invalid = true;
-                break;
-            }
-        }
-        if (invalid) {
-            throw new ParameterException(spec.commandLine(),
-                    String.format("Invalid value '%s' for option '--prime': " +
-                            "value is not a prime number.", value));
-        }
-        prime = value;
-    }
-    // ...
-}
+
class SingleOptionValidationExample {
+    private int prime;
+
+    @Spec CommandSpec spec; // injected by picocli
+
+    @Option(names = {"-p", "--prime"}, paramLabel = "NUMBER")
+    public void setPrimeNumber(int value) {
+        boolean invalid = false;
+        for (int i = 2; i <= value / 2; i++) {
+            if (value % i == 0) {
+                invalid = true;
+                break;
+            }
+        }
+        if (invalid) {
+            throw new ParameterException(spec.commandLine(),
+                    String.format("Invalid value '%s' for option '--prime': " +
+                            "value is not a prime number.", value));
+        }
+        prime = value;
+    }
+    // ...
+}

Kotlin
-
class SingleOptionValidationExample {
-    private var prime = 0
+
class SingleOptionValidationExample {
+    private var prime = 0
 
-    @Spec lateinit var spec : CommandSpec // injected by picocli
+    @Spec lateinit var spec : CommandSpec // injected by picocli
 
-    @Option(names = ["-p", "--prime"], paramLabel = "NUMBER")
-    fun setPrimeNumber(value: Int) {
-        var invalid = false
-        for (i in 2..value / 2) {
-            if (value % i == 0) {
-                invalid = true
-                break
-            }
-        }
-        if (invalid) {
-            throw ParameterException(spec.commandLine(),
-                String.format("Invalid value '%s' for option '--prime': " +
-                              "value is not a prime number.", value))
-        }
-        prime = value
-    }
-    // ...
-}
+ @Option(names = ["-p", "--prime"], paramLabel = "NUMBER") + fun setPrimeNumber(value: Int) { + var invalid = false + for (i in 2..value / 2) { + if (value % i == 0) { + invalid = true + break + } + } + if (invalid) { + throw ParameterException(spec.commandLine(), + String.format("Invalid value '%s' for option '--prime': " + + "value is not a prime number.", value)) + } + prime = value + } + // ... +}

@@ -7281,71 +7006,71 @@

Java
-
@Command(name = "myapp", mixinStandardHelpOptions = true, version = "myapp 0.1")
-class MultiOptionValidationExample implements Runnable {
-    @Option(names="--xml")  List<File> xmlFiles;
-    @Option(names="--csv")  List<File> csvFiles;
-    @Option(names="--json") List<File> jsonFiles;
+
@Command(name = "myapp", mixinStandardHelpOptions = true, version = "myapp 0.1")
+class MultiOptionValidationExample implements Runnable {
+    @Option(names="--xml")  List<File> xmlFiles;
+    @Option(names="--csv")  List<File> csvFiles;
+    @Option(names="--json") List<File> jsonFiles;
 
-    @Spec CommandSpec spec; // injected by picocli
+    @Spec CommandSpec spec; // injected by picocli
 
-    public static void main(String... args) {
-        System.exit(new CommandLine(new MultiOptionValidationExample()).execute(args));
-    }
+    public static void main(String... args) {
+        System.exit(new CommandLine(new MultiOptionValidationExample()).execute(args));
+    }
 
-    public void run() {
-        validate();
+    public void run() {
+        validate();
 
-        // remaining business logic here
-    }
+        // remaining business logic here
+    }
 
-    private void validate() {
-        if (missing(xmlFiles) && missing(csvFiles) && missing(jsonFiles)) {
-            throw new ParameterException(spec.commandLine(),
-                    "Missing option: at least one of the " +
-                    "'--xml', '--csv', or '--json' options must be specified.");
-        }
-    }
+    private void validate() {
+        if (missing(xmlFiles) && missing(csvFiles) && missing(jsonFiles)) {
+            throw new ParameterException(spec.commandLine(),
+                    "Missing option: at least one of the " +
+                    "'--xml', '--csv', or '--json' options must be specified.");
+        }
+    }
 
-    private boolean missing(List<?> list) {
-        return list == null || list.isEmpty();
-    }
-}
+ private boolean missing(List<?> list) { + return list == null || list.isEmpty(); + } +}

Kotlin
-
@Command(name = "myapp", mixinStandardHelpOptions = true, version = ["myapp 0.1"])
-class MultiOptionValidationExample : Runnable {
-    @Option(names = ["--xml"])  var xmlFiles: List<File>? = null
-    @Option(names = ["--csv"])  var csvFiles: List<File>? = null
-    @Option(names = ["--json"]) var jsonFiles: List<File>? = null
+
@Command(name = "myapp", mixinStandardHelpOptions = true, version = ["myapp 0.1"])
+class MultiOptionValidationExample : Runnable {
+    @Option(names = ["--xml"])  var xmlFiles: List<File>? = null
+    @Option(names = ["--csv"])  var csvFiles: List<File>? = null
+    @Option(names = ["--json"]) var jsonFiles: List<File>? = null
 
-    @Spec lateinit var spec : CommandSpec // injected by picocli
+    @Spec lateinit var spec : CommandSpec // injected by picocli
 
-     override fun run() {
-        validate()
+     override fun run() {
+        validate()
 
-        // remaining business logic here
-    }
+        // remaining business logic here
+    }
 
-    private fun validate() {
-        if (missing(xmlFiles) && missing(csvFiles) && missing(jsonFiles)) {
-            throw ParameterException(spec.commandLine(),
-                "Missing option: at least one of the " +
-                "'--xml', '--csv', or '--json' options must be specified.")
-        }
-    }
+    private fun validate() {
+        if (missing(xmlFiles) && missing(csvFiles) && missing(jsonFiles)) {
+            throw ParameterException(spec.commandLine(),
+                "Missing option: at least one of the " +
+                "'--xml', '--csv', or '--json' options must be specified.")
+        }
+    }
 
-    private fun missing(list: List<*>?): Boolean {
-        return list == null || list.isEmpty()
-    }
-}
+    private fun missing(list: List<*>?): Boolean {
+        return list == null || list.isEmpty()
+    }
+}
 
-fun main(args: Array<String>) {
-    exitProcess(CommandLine(MultiOptionValidationExample()).execute(*args))
-}
+fun main(args: Array<String>) { + exitProcess(CommandLine(MultiOptionValidationExample()).execute(*args)) +}

@@ -7363,123 +7088,123 @@

Java
-
import picocli.CommandLine;
-import picocli.CommandLine.Model.CommandSpec;
-import picocli.CommandLine.*;
+
import picocli.CommandLine;
+import picocli.CommandLine.Model.CommandSpec;
+import picocli.CommandLine.*;
 
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.constraints.*;
-import java.util.Set;
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.constraints.*;
+import java.util.Set;
 
-// Example inspired by https://www.baeldung.com/javax-validation
-public class User implements Runnable {
+// Example inspired by https://www.baeldung.com/javax-validation
+public class User implements Runnable {
 
-    @NotNull(message = "Name cannot be null")
-    @Option(names = {"-n", "--name"}, description = "mandatory")
-    private String name;
+    @NotNull(message = "Name cannot be null")
+    @Option(names = {"-n", "--name"}, description = "mandatory")
+    private String name;
 
-    @Min(value = 18, message = "Age should not be less than 18")
-    @Max(value = 150, message = "Age should not be greater than 150")
-    @Option(names = {"-a", "--age"}, description = "between 18-150")
-    private int age;
+    @Min(value = 18, message = "Age should not be less than 18")
+    @Max(value = 150, message = "Age should not be greater than 150")
+    @Option(names = {"-a", "--age"}, description = "between 18-150")
+    private int age;
 
-    @Email(message = "Email should be valid")
-    @Option(names = {"-e", "--email"}, description = "valid email")
-    private String email;
+    @Email(message = "Email should be valid")
+    @Option(names = {"-e", "--email"}, description = "valid email")
+    private String email;
 
-    @Spec CommandSpec spec;
+    @Spec CommandSpec spec;
 
-    public User() { }
+    public User() { }
 
-    @Override
-    public String toString() {
-        return String.format("User{name='%s', age=%s, email='%s'}", name, age, email);
-    }
+    @Override
+    public String toString() {
+        return String.format("User{name='%s', age=%s, email='%s'}", name, age, email);
+    }
 
-    public static void main(String... args) {
-        new CommandLine(new User()).execute(args);
-    }
+    public static void main(String... args) {
+        new CommandLine(new User()).execute(args);
+    }
 
-    @Override
-    public void run() {
-        validate();
+    @Override
+    public void run() {
+        validate();
 
-        // remaining business logic here
-    }
+        // remaining business logic here
+    }
 
-    private void validate() {
-        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
-        Set<ConstraintViolation<User>> violations = validator.validate(this);
+    private void validate() {
+        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
+        Set<ConstraintViolation<User>> violations = validator.validate(this);
 
-        if (!violations.isEmpty()) {
-            String errorMsg = "";
-            for (ConstraintViolation<User> violation : violations) {
-                errorMsg += "ERROR: " + violation.getMessage() + "\n";
-            }
-            throw new ParameterException(spec.commandLine(), errorMsg);
-        }
-    }
-}
+ if (!violations.isEmpty()) { + String errorMsg = ""; + for (ConstraintViolation<User> violation : violations) { + errorMsg += "ERROR: " + violation.getMessage() + "\n"; + } + throw new ParameterException(spec.commandLine(), errorMsg); + } + } +}

Kotlin
-
import picocli.CommandLine
-import picocli.CommandLine.Model.CommandSpec
-import picocli.CommandLine.*
+
import picocli.CommandLine
+import picocli.CommandLine.Model.CommandSpec
+import picocli.CommandLine.*
 
-import javax.validation.ConstraintViolation
-import javax.validation.Validation
-import javax.validation.Validator
-import javax.validation.constraints.*
+import javax.validation.ConstraintViolation
+import javax.validation.Validation
+import javax.validation.Validator
+import javax.validation.constraints.*
 
-// Example inspired by https://www.baeldung.com/javax-validation
-class User : Runnable {
+// Example inspired by https://www.baeldung.com/javax-validation
+class User : Runnable {
 
-    @NotNull(message = "Name cannot be null")
-    @CommandLine.Option(names = ["-n", "--name"], description = ["mandatory"])
-    private lateinit var name: String
+    @NotNull(message = "Name cannot be null")
+    @CommandLine.Option(names = ["-n", "--name"], description = ["mandatory"])
+    private lateinit var name: String
 
-    @Min(value = 18, message = "Age should not be less than 18")
-    @Max(value = 150, message = "Age should not be greater than 150")
-    @Option(names = ["-a", "--age"], description = ["between 18-150"])
-    private var age = 0
+    @Min(value = 18, message = "Age should not be less than 18")
+    @Max(value = 150, message = "Age should not be greater than 150")
+    @Option(names = ["-a", "--age"], description = ["between 18-150"])
+    private var age = 0
 
-    @Email(message = "Email should be valid")
-    @Option(names = ["-e", "--email"], description = ["valid email"])
-    private lateinit var email: String
+    @Email(message = "Email should be valid")
+    @Option(names = ["-e", "--email"], description = ["valid email"])
+    private lateinit var email: String
 
-    @Spec
-    lateinit var spec: CommandSpec
-    override fun toString(): String {
-        return "User{name=$name, age=$age, email=$email}"
-    }
+    @Spec
+    lateinit var spec: CommandSpec
+    override fun toString(): String {
+        return "User{name=$name, age=$age, email=$email}"
+    }
 
-    override fun run() {
-        validate()
+    override fun run() {
+        validate()
 
-        // remaining business logic here
-    }
+        // remaining business logic here
+    }
 
-    private fun validate() {
-        val validator: Validator = Validation.buildDefaultValidatorFactory().validator
-        val violations: Set<ConstraintViolation<User>> = validator.validate(this)
-        if (violations.isNotEmpty()) {
-            var errorMsg = ""
-            for (violation in violations) {
-                errorMsg += "ERROR: ${violation.message}\n"
-            }
-            throw CommandLine.ParameterException(spec.commandLine(), errorMsg)
-        }
-    }
-}
+    private fun validate() {
+        val validator: Validator = Validation.buildDefaultValidatorFactory().validator
+        val violations: Set<ConstraintViolation<User>> = validator.validate(this)
+        if (violations.isNotEmpty()) {
+            var errorMsg = ""
+            for (violation in violations) {
+                errorMsg += "ERROR: ${violation.message}\n"
+            }
+            throw CommandLine.ParameterException(spec.commandLine(), errorMsg)
+        }
+    }
+}
 
-fun main(args: Array<String>) {
-    CommandLine(User()).execute(*args)
-}
+fun main(args: Array<String>) { + CommandLine(User()).execute(*args) +}
@@ -7611,33 +7336,33 @@

Java
-
class AbbreviationsAndPosix {
-    @Option(names = "-A")      boolean a;
-    @Option(names = "-B")      boolean b;
-    @Option(names = "-AaaBbb") boolean aaaBbb;
-}
+
class AbbreviationsAndPosix {
+    @Option(names = "-A")      boolean a;
+    @Option(names = "-B")      boolean b;
+    @Option(names = "-AaaBbb") boolean aaaBbb;
+}
 
-AbbreviationsAndPosix app = new AbbreviationsAndPosix();
-new CommandLine(app).setAbbreviatedOptionsAllowed(true).parseArgs("-AB");
-assert app.aaaBbb == true; // the long option is matched from abbreviated input -AB
-assert app.a == false;
-assert app.b == false;
+AbbreviationsAndPosix app = new AbbreviationsAndPosix(); +new CommandLine(app).setAbbreviatedOptionsAllowed(true).parseArgs("-AB"); +assert app.aaaBbb == true; // the long option is matched from abbreviated input -AB +assert app.a == false; +assert app.b == false;
Kotlin
-
class AbbreviationsAndPosix {
-    @Option(names = ["-A"])       var a = false
-    @Option(names = ["-B"])       var b = false
-    @Option(names = ["-AaaBbb"])  var aaaBbb = false
-}
+
class AbbreviationsAndPosix {
+    @Option(names = ["-A"])       var a = false
+    @Option(names = ["-B"])       var b = false
+    @Option(names = ["-AaaBbb"])  var aaaBbb = false
+}
 
-val app = AbbreviationsAndPosix()
-CommandLine(app).setAbbreviatedOptionsAllowed(true).parseArgs("-AB")
-assertTrue(app.aaaBbb) // the long option is matched from abbreviated input -AB
-assertFalse(app.a)
-assertFalse(app.b)
+val app = AbbreviationsAndPosix() +CommandLine(app).setAbbreviatedOptionsAllowed(true).parseArgs("-AB") +assertTrue(app.aaaBbb) // the long option is matched from abbreviated input -AB +assertFalse(app.a) +assertFalse(app.b)
Kotlin
-
@Option(names = ["-p"]) var port = 0
+
@Option(names = ["-p"]) var port = 0
@@ -7708,17 +7433,17 @@

11.6. U
Java
-
class OnlyThree {
-    @Parameters(arity = "3") String[] values;
-}
+
class OnlyThree {
+    @Parameters(arity = "3") String[] values;
+}
Kotlin
-
class OnlyThree {
-    @Parameters(arity = "3") lateinit var values: Array<String>
-}
+
class OnlyThree {
+    @Parameters(arity = "3") lateinit var values: Array<String>
+}
Kotlin
-
@Option(names = ["-x"]) lateinit var x: String
-@Option(names = ["-y"]) lateinit var y: String
-@Parameters lateinit var remainder: Array<String>
+
@Option(names = ["-x"]) lateinit var x: String
+@Option(names = ["-y"]) lateinit var y: String
+@Parameters lateinit var remainder: Array<String>
Kotlin
-
class MyApp {
-    @Option(names = ["-x"]) lateinit var x: String
-}
+
class MyApp {
+    @Option(names = ["-x"]) lateinit var x: String
+}
Kotlin
-
val app = MyApp()
-CommandLine(app).parseArgs("-x", "-z")
-assertEquals("-z", app.x)
+
val app = MyApp()
+CommandLine(app).parseArgs("-x", "-z")
+assertEquals("-z", app.x)
Kotlin
-
CommandLine(MyApp())
-        .setUnmatchedOptionsAllowedAsOptionParameters(false)
-        .parseArgs("-x", "-z")
+
CommandLine(MyApp())
+        .setUnmatchedOptionsAllowedAsOptionParameters(false)
+        .parseArgs("-x", "-z")
Kotlin
-
class App {
-    @Option(names = ["-x"]) var x: String? = null
-    @Option(names = ["-y"]) var y: String? = null
-}
+
class App {
+    @Option(names = ["-x"]) var x: String? = null
+    @Option(names = ["-y"]) var y: String? = null
+}
 
-fun main(args: Array<String>) {
-    val app = App()
-    CommandLine(app).setTrimQuotes(true).parseArgs(*args)
-    println("x='${app.x}', y='${app.y}'")
-}
+fun main(args: Array<String>) { + val app = App() + CommandLine(app).setTrimQuotes(true).parseArgs(*args) + println("x='${app.x}', y='${app.y}'") +}

@@ -8093,15 +7818,15 @@

Java
-
@Option(names = "-x", split = ",")
-String[] parts;
+
@Option(names = "-x", split = ",")
+String[] parts;
Kotlin
-
@Option(names = ["-x"], split = ",")
-lateinit var parts: Array<String>
+
@Option(names = ["-x"], split = ",")
+lateinit var parts: Array<String>
Kotlin
-
@Command(name = "find")
-class Find {
-    @Option(names = ["-exec"], parameterConsumer = ExecParameterConsumer::class)
-    var list: List<String> = ArrayList()
-}
+
@Command(name = "find")
+class Find {
+    @Option(names = ["-exec"], parameterConsumer = ExecParameterConsumer::class)
+    var list: List<String> = ArrayList()
+}
 
-class ExecParameterConsumer : IParameterConsumer {
-    override fun consumeParameters(args: Stack<String>, argSpec: ArgSpec, commandSpec: CommandSpec) {
-        val list = argSpec.getValue<MutableList<String>>()
-        while (!args.isEmpty()) {
-            val arg = args.pop()
-            list.add(arg)
+class ExecParameterConsumer : IParameterConsumer {
+    override fun consumeParameters(args: Stack<String>, argSpec: ArgSpec, commandSpec: CommandSpec) {
+        val list = argSpec.getValue<MutableList<String>>()
+        while (!args.isEmpty()) {
+            val arg = args.pop()
+            list.add(arg)
 
-            // `find -exec` semantics: stop processing after a ';' or '+' argument
-            if (";".equals(arg) || "+".equals(arg)) {
-                break
-            }
-        }
-    }
-}
+ // `find -exec` semantics: stop processing after a ';' or '+' argument + if (";".equals(arg) || "+".equals(arg)) { + break + } + } + } +}
@@ -8399,76 +8124,76 @@
Examp
Java
-
@Command(name = "edit")
-class Edit {
-
-    @Parameters(index = "0", arity="0..1", description = "The file to edit.")
-    File file;
-
-    enum Editor { defaultEditor, eclipse, idea, netbeans }
-
-    @Option(names = "--open", arity = "0..1", preprocessor = Edit.MyPreprocessor.class,
-        description = {
-           "Optionally specify the editor to use (${COMPLETION-CANDIDATES}). " +
-           "If omitted the default editor is used. ",
-           "Example: edit --open=idea FILE opens IntelliJ IDEA (notice the '=' separator)",
-           "         edit --open FILE opens the specified file in the default editor"
-        })
-    Editor editor = Editor.defaultEditor;
-
-    static class MyPreprocessor implements IParameterPreprocessor {
-        public boolean preprocess(Stack<String> args,
-                                  CommandSpec commandSpec,
-                                  ArgSpec argSpec,
-                                  Map<String, Object> info) {
-            // we need to decide whether the next arg is the file to edit
-            // or the name of the editor to use...
-            if (" ".equals(info.get("separator"))) { // parameter was not attached to option
-
-                // act as if the user specified --open=defaultEditor
-                args.push(Editor.defaultEditor.name());
-            }
-            return false; // picocli's internal parsing is resumed for this option
-        }
-    }
-}
+
@Command(name = "edit")
+class Edit {
+
+    @Parameters(index = "0", arity="0..1", description = "The file to edit.")
+    File file;
+
+    enum Editor { defaultEditor, eclipse, idea, netbeans }
+
+    @Option(names = "--open", arity = "0..1", preprocessor = Edit.MyPreprocessor.class,
+        description = {
+           "Optionally specify the editor to use (${COMPLETION-CANDIDATES}). " +
+           "If omitted the default editor is used. ",
+           "Example: edit --open=idea FILE opens IntelliJ IDEA (notice the '=' separator)",
+           "         edit --open FILE opens the specified file in the default editor"
+        })
+    Editor editor = Editor.defaultEditor;
+
+    static class MyPreprocessor implements IParameterPreprocessor {
+        public boolean preprocess(Stack<String> args,
+                                  CommandSpec commandSpec,
+                                  ArgSpec argSpec,
+                                  Map<String, Object> info) {
+            // we need to decide whether the next arg is the file to edit
+            // or the name of the editor to use...
+            if (" ".equals(info.get("separator"))) { // parameter was not attached to option
+
+                // act as if the user specified --open=defaultEditor
+                args.push(Editor.defaultEditor.name());
+            }
+            return false; // picocli's internal parsing is resumed for this option
+        }
+    }
+}
Kotlin
-
class Edit : Runnable {
-
-    @Parameters(index = "0", arity = "0..1", description = ["The file to edit."])
-    var file: File? = null
-
-    enum class Editor { defaultEditor, eclipse, idea, netbeans }
-
-    @Option(names = ["--open"], arity = "0..1", preprocessor = MyPreprocessor::class,
-        description = ["Optionally specify the editor to use (\${COMPLETION-CANDIDATES}). " +
-            "If omitted the default editor is used. ",
-            "Example: edit --open=idea FILE ",
-            "  opens file in IntelliJ IDEA (notice the '=' separator)",
-            "         edit --open FILE",
-            "  opens the specified file in the default editor"])
-    var editor = Editor.defaultEditor
-
-    class MyPreprocessor : IParameterPreprocessor {
-        override fun preprocess(args: Stack<String>,
-                                commandSpec: CommandSpec,
-                                argSpec: ArgSpec,
-                                info: Map<String, Any>): Boolean {
-            // we need to decide whether the next arg is the file to edit
-            // or the name of the editor to use ...
-            if (" " == info["separator"]) { // parameter was not attached to option
-
-                // act as if the user specified --open=defaultEditor
-                args.push(Editor.defaultEditor.name)
-            }
-            return false // picocli's internal parsing is resumed for this option
-        }
-    }
-}
+
class Edit : Runnable {
+
+    @Parameters(index = "0", arity = "0..1", description = ["The file to edit."])
+    var file: File? = null
+
+    enum class Editor { defaultEditor, eclipse, idea, netbeans }
+
+    @Option(names = ["--open"], arity = "0..1", preprocessor = MyPreprocessor::class,
+        description = ["Optionally specify the editor to use (\${COMPLETION-CANDIDATES}). " +
+            "If omitted the default editor is used. ",
+            "Example: edit --open=idea FILE ",
+            "  opens file in IntelliJ IDEA (notice the '=' separator)",
+            "         edit --open FILE",
+            "  opens the specified file in the default editor"])
+    var editor = Editor.defaultEditor
+
+    class MyPreprocessor : IParameterPreprocessor {
+        override fun preprocess(args: Stack<String>,
+                                commandSpec: CommandSpec,
+                                argSpec: ArgSpec,
+                                info: Map<String, Any>): Boolean {
+            // we need to decide whether the next arg is the file to edit
+            // or the name of the editor to use ...
+            if (" " == info["separator"]) { // parameter was not attached to option
+
+                // act as if the user specified --open=defaultEditor
+                args.push(Editor.defaultEditor.name)
+            }
+            return false // picocli's internal parsing is resumed for this option
+        }
+    }
+}
@@ -8556,21 +8281,21 @@

12.1. Help Op
Java
-
@Option(names = {"-V", "--version"}, versionHelp = true, description = "display version info")
-boolean versionInfoRequested;
+
@Option(names = {"-V", "--version"}, versionHelp = true, description = "display version info")
+boolean versionInfoRequested;
 
-@Option(names = {"-h", "--help"}, usageHelp = true, description = "display this help message")
-boolean usageHelpRequested;
+@Option(names = {"-h", "--help"}, usageHelp = true, description = "display this help message") +boolean usageHelpRequested;
Kotlin
-
@Option(names = ["-V", "--version"], versionHelp = true, description = ["display version info"])
-var versionInfoRequested = false
+
@Option(names = ["-V", "--version"], versionHelp = true, description = ["display version info"])
+var versionInfoRequested = false
 
-@Option(names = ["-h", "--help"], usageHelp = true, description = ["display this help message"])
-var usageHelpRequested = false
+@Option(names = ["-h", "--help"], usageHelp = true, description = ["display this help message"]) +var usageHelpRequested = false
@@ -8579,21 +8304,21 @@

12.1. Help Op
Java
-
App app = CommandLine.populateCommand(new App(), args);
-if (app.usageHelpRequested) {
-    CommandLine.usage(new App(), System.out);
-    return;
-}
+
App app = CommandLine.populateCommand(new App(), args);
+if (app.usageHelpRequested) {
+    CommandLine.usage(new App(), System.out);
+    return;
+}
Kotlin
-
val app: App = CommandLine.populateCommand(App(), *args)
-if (app.usageHelpRequested) {
-    CommandLine.usage(App(), System.out)
-    return
-}
+
val app: App = CommandLine.populateCommand(App(), *args)
+if (app.usageHelpRequested) {
+    CommandLine.usage(App(), System.out)
+    return
+}
@@ -8613,31 +8338,31 @@

12.1. Help Op
Java
-
CommandLine commandLine = new CommandLine(new App());
-commandLine.parseArgs(args);
-if (commandLine.isUsageHelpRequested()) {
-    commandLine.usage(System.out);
-    return;
-} else if (commandLine.isVersionHelpRequested()) {
-    commandLine.printVersionHelp(System.out);
-    return;
-}
-// ... run App's business logic
+
CommandLine commandLine = new CommandLine(new App());
+commandLine.parseArgs(args);
+if (commandLine.isUsageHelpRequested()) {
+    commandLine.usage(System.out);
+    return;
+} else if (commandLine.isVersionHelpRequested()) {
+    commandLine.printVersionHelp(System.out);
+    return;
+}
+// ... run App's business logic
Kotlin
-
val commandLine = CommandLine(App())
-commandLine.parseArgs(*args)
-if (commandLine.isUsageHelpRequested) {
-    commandLine.usage(System.out)
-    return
-} else if (commandLine.isVersionHelpRequested) {
-    commandLine.printVersionHelp(System.out)
-    return
-}
-// ... run App's business logic
+
val commandLine = CommandLine(App())
+commandLine.parseArgs(*args)
+if (commandLine.isUsageHelpRequested) {
+    commandLine.usage(System.out)
+    return
+} else if (commandLine.isVersionHelpRequested) {
+    commandLine.printVersionHelp(System.out)
+    return
+}
+// ... run App's business logic
Kotlin
-
@Command(mixinStandardHelpOptions = true, version = ["auto help demo - picocli 3.0"])
-class AutoHelpDemo : Runnable {
+
@Command(mixinStandardHelpOptions = true, version = ["auto help demo - picocli 3.0"])
+class AutoHelpDemo : Runnable {
 
-    @Option(names = ["--option"], description = ["Some option."])
-    lateinit var option: String
+    @Option(names = ["--option"], description = ["Some option."])
+    lateinit var option: String
 
-    override fun run() { /* ... */ }
-}
+ override fun run() { /* ... */ } +}
Kotlin
-
import picocli.CommandLine.HelpCommand
-// ...
+
import picocli.CommandLine.HelpCommand
+// ...
 
-@Command(name = "myapp", subcommands = [HelpCommand::class, Subcommand::class])
-class MyCommand : Runnable {
-    // ...
-}
+@Command(name = "myapp", subcommands = [HelpCommand::class, Subcommand::class]) +class MyCommand : Runnable { + // ... +}

@@ -8742,7 +8467,7 @@

-
@Command(helpCommand = true)
+
@Command(helpCommand = true)

@@ -8846,23 +8571,23 @@

Java
-
@Command(version = "1.0")
-class VersionedCommand {
-    @Option(names = { "-V", "--version" }, versionHelp = true,
-            description = "print version information and exit")
-    boolean versionRequested;
-    /* ... */ }
+
@Command(version = "1.0")
+class VersionedCommand {
+    @Option(names = { "-V", "--version" }, versionHelp = true,
+            description = "print version information and exit")
+    boolean versionRequested;
+    /* ... */ }

Kotlin
-
@Command(version = ["1.0"])
-class VersionedCommand {
-    @Option(names = ["-V", "--version"], versionHelp = true,
-            description = ["print version information and exit"])
-    var versionRequested = false
-    /* ... */ }
+
@Command(version = ["1.0"])
+class VersionedCommand {
+    @Option(names = ["-V", "--version"], versionHelp = true,
+            description = ["print version information and exit"])
+    var versionRequested = false
+    /* ... */ }
Kotlin
-
val commandLine = CommandLine(VersionedCommand())
-commandLine.parseArgs(*args)
-if (commandLine.isVersionHelpRequested) {
-    commandLine.printVersionHelp(System.out)
-    return
-}
+
val commandLine = CommandLine(VersionedCommand())
+commandLine.parseArgs(*args)
+if (commandLine.isVersionHelpRequested) {
+    commandLine.printVersionHelp(System.out)
+    return
+}
@@ -8900,15 +8625,15 @@

Java
-
@Command(version = { "Versioned Command 1.0", "Build 12345", "(c) 2017" })
-class VersionedCommand { /* ... */ }
+
@Command(version = { "Versioned Command 1.0", "Build 12345", "(c) 2017" })
+class VersionedCommand { /* ... */ }
Kotlin
-
@Command(version = ["Versioned Command 1.0", "Build 12345", "(c) 2017"])
-class VersionedCommand { /* */ }
+
@Command(version = ["Versioned Command 1.0", "Build 12345", "(c) 2017"])
+class VersionedCommand { /* */ }
Kotlin
-
@Command(version = [
-    "Versioned Command 1.0",
-    "Picocli " + picocli.CommandLine.VERSION,
-    "JVM: \${java.version} (\${java.vendor} \${java.vm.name} \${java.vm.version})",
-    "OS: \${os.name} \${os.version} \${os.arch}"])
-class VersionedCommand { /* */ }
+
@Command(version = [
+    "Versioned Command 1.0",
+    "Picocli " + picocli.CommandLine.VERSION,
+    "JVM: \${java.version} (\${java.vendor} \${java.vm.name} \${java.vm.version})",
+    "OS: \${os.name} \${os.version} \${os.arch}"])
+class VersionedCommand { /* */ }
Kotlin
-
@Command(version = [
-        "@|yellow Versioned Command 1.0|@",
-        "@|blue Build 12345|@",
-        "@|red,bg(white) (c) 2017|@"])
-class VersionedCommand { /* */ }
+
@Command(version = [
+        "@|yellow Versioned Command 1.0|@",
+        "@|blue Build 12345|@",
+        "@|red,bg(white) (c) 2017|@"])
+class VersionedCommand { /* */ }
Kotlin
-
@Command(version = [
-        "Versioned Command 1.0",
-        "Build %1\$s",
-        "(c) 2017, licensed to %2\$s"])
-class VersionedCommand { /* ... */ }
+
@Command(version = [
+        "Versioned Command 1.0",
+        "Build %1\$s",
+        "(c) 2017, licensed to %2\$s"])
+class VersionedCommand { /* ... */ }
Kotlin
-
val args = arrayOf("1234", System.getProperty("user.name"))
-CommandLine(VersionedCommand()).printVersionHelp(System.out, Help.Ansi.AUTO, *args)
+
val args = arrayOf("1234", System.getProperty("user.name"))
+CommandLine(VersionedCommand()).printVersionHelp(System.out, Help.Ansi.AUTO, *args)
@@ -9050,15 +8775,15 @@

Java
-
@Command(versionProvider = com.my.custom.ManifestVersionProvider.class)
-class App { /* ... */ }
+
@Command(versionProvider = com.my.custom.ManifestVersionProvider.class)
+class App { /* ... */ }
Kotlin
-
@Command(versionProvider = com.my.custom.ManifestVersionProvider::class)
-class App { /* ... */ }
+
@Command(versionProvider = com.my.custom.ManifestVersionProvider::class)
+class App { /* ... */ }
Kotlin
-
class VersionProviderWithVariables : IVersionProvider {
-    override fun getVersion(): Array<String> {
-        return arrayOf("\${COMMAND-FULL-NAME} version 1.0")
-    }
-}
+
class VersionProviderWithVariables : IVersionProvider {
+    override fun getVersion(): Array<String> {
+        return arrayOf("\${COMMAND-FULL-NAME} version 1.0")
+    }
+}
Kotlin
-
class MyVersionProvider : IVersionProvider {
-    @Spec
-    lateinit var spec: CommandSpec
+
class MyVersionProvider : IVersionProvider {
+    @Spec
+    lateinit var spec: CommandSpec
 
-    override fun getVersion(): Array<String> {
-        return arrayOf("Version info for " + spec.qualifiedName())
-    }
-}
+ override fun getVersion(): Array<String> { + return arrayOf("Version info for " + spec.qualifiedName()) + } +}
@@ -9203,43 +8928,43 @@

14.1. C
Java
-
@Command(name = "cat", footer = "Copyright(c) 2017",
-         description = "Concatenate FILE(s), or standard input, to standard output.")
-class Cat {
+
@Command(name = "cat", footer = "Copyright(c) 2017",
+         description = "Concatenate FILE(s), or standard input, to standard output.")
+class Cat {
 
-    @Parameters(paramLabel = "FILE", description = "Files whose contents to display")
-    List<File> files;
+    @Parameters(paramLabel = "FILE", description = "Files whose contents to display")
+    List<File> files;
 
-    @Option(names = "--help", usageHelp = true, description = "display this help and exit")
-    boolean help;
+    @Option(names = "--help", usageHelp = true, description = "display this help and exit")
+    boolean help;
 
-    @Option(names = "-t",                 description = "equivalent to -vT")  boolean t;
-    @Option(names = "-e",                 description = "equivalent to -vE")  boolean e;
-    @Option(names = {"-A", "--show-all"}, description = "equivalent to -vET") boolean all;
+    @Option(names = "-t",                 description = "equivalent to -vT")  boolean t;
+    @Option(names = "-e",                 description = "equivalent to -vE")  boolean e;
+    @Option(names = {"-A", "--show-all"}, description = "equivalent to -vET") boolean all;
 
-    // ...
-}
+ // ... +}
Kotlin
-
@Command(name = "cat", footer = ["Copyright(c) 2017"],
-         description = ["Concatenate FILE(s), or standard input, to standard output."])
-class Cat {
+
@Command(name = "cat", footer = ["Copyright(c) 2017"],
+         description = ["Concatenate FILE(s), or standard input, to standard output."])
+class Cat {
 
-    @Parameters(paramLabel = "FILE", description = ["Files whose contents to display"])
-    lateinit var files: List<File>
+    @Parameters(paramLabel = "FILE", description = ["Files whose contents to display"])
+    lateinit var files: List<File>
 
-    @Option(names = ["--help"], usageHelp = true, description = ["display this help and exit"])
-    var help = false
+    @Option(names = ["--help"], usageHelp = true, description = ["display this help and exit"])
+    var help = false
 
-    @Option(names = ["-t"],               description = ["equivalent to -vT"])  var t = false
-    @Option(names = ["-e"],               description = ["equivalent to -vE"])  var e = false
-    @Option(names = ["-A", "--show-all"], description = ["equivalent to -vET"]) var all = false
+    @Option(names = ["-t"],               description = ["equivalent to -vT"])  var t = false
+    @Option(names = ["-e"],               description = ["equivalent to -vE"])  var e = false
+    @Option(names = ["-A", "--show-all"], description = ["equivalent to -vET"]) var all = false
 
-    // ...
-}
+ // ... +}
@@ -9250,7 +8975,7 @@

14.2. Command
-
@Command(name = "cat")
+
@Command(name = "cat")
@@ -9284,32 +9009,32 @@

14.3.
Java
-
@Command()
-class ParamLabels {
-    @Option(names = "-f",    description = "a file",       paramLabel = "FILE") File f;
-    @Option(names = "-n",    description = "a number option")                   int number;
-    @Parameters(index = "0", description = "number param", paramLabel = "NUM")  int n;
-    @Parameters(index = "1", description = "the host parameter")                InetAddress host;
-}
+
@Command()
+class ParamLabels {
+    @Option(names = "-f",    description = "a file",       paramLabel = "FILE") File f;
+    @Option(names = "-n",    description = "a number option")                   int number;
+    @Parameters(index = "0", description = "number param", paramLabel = "NUM")  int n;
+    @Parameters(index = "1", description = "the host parameter")                InetAddress host;
+}
Kotlin
-
@Command
-class ParamLabels {
-    @Option(names = ["-f"], description = ["a file"], paramLabel = "FILE")
-    lateinit var f: File
+
@Command
+class ParamLabels {
+    @Option(names = ["-f"], description = ["a file"], paramLabel = "FILE")
+    lateinit var f: File
 
-    @Option(names = ["-n"], description = ["a number option"])
-    var number = 0
+    @Option(names = ["-n"], description = ["a number option"])
+    var number = 0
 
-    @Parameters(index = "0", description = ["number param"], paramLabel = "NUM")
-    var n = 0
+    @Parameters(index = "0", description = ["number param"], paramLabel = "NUM")
+    var n = 0
 
-    @Parameters(index = "1", description = ["the host parameter"])
-    lateinit var host: InetAddress
-}
+ @Parameters(index = "1", description = ["the host parameter"]) + lateinit var host: InetAddress +}
@@ -9334,7 +9059,7 @@

<

-
@Command(sortOptions = false)
+
@Command(sortOptions = false)

@@ -9356,24 +9081,24 @@

Java
-
@Command(requiredOptionMarker = '*', abbreviateSynopsis = true)
-class Example {
-    @Option(names = {"-a", "--alpha"}, description = "optional alpha") String alpha;
-    @Option(names = {"-b", "--beta"}, required = true, description = "mandatory beta") String beta;
-}
+
@Command(requiredOptionMarker = '*', abbreviateSynopsis = true)
+class Example {
+    @Option(names = {"-a", "--alpha"}, description = "optional alpha") String alpha;
+    @Option(names = {"-b", "--beta"}, required = true, description = "mandatory beta") String beta;
+}
Kotlin
-
@Command(requiredOptionMarker = '*', abbreviateSynopsis = true)
-class Example {
-    @Option(names = ["-a", "--alpha"], description = ["optional alpha"])
-    lateinit var alpha: String
+
@Command(requiredOptionMarker = '*', abbreviateSynopsis = true)
+class Example {
+    @Option(names = ["-a", "--alpha"], description = ["optional alpha"])
+    lateinit var alpha: String
 
-    @Option(names = ["-b", "--beta"], required = true, description = ["mandatory beta"])
-    lateinit var beta: String
-}
+ @Option(names = ["-b", "--beta"], required = true, description = ["mandatory beta"]) + lateinit var beta: String +}
@@ -9511,15 +9236,15 @@

<
Java
-
@Parameters(split = "\\+", splitSynopsisLabel = "+", paramLabel = "VALUE")
-List<String> values;
+
@Parameters(split = "\\+", splitSynopsisLabel = "+", paramLabel = "VALUE")
+List<String> values;
Kotlin
-
@Parameters(split = "\\+", splitSynopsisLabel = "+", paramLabel = "VALUE")
-lateinit var values: List<String>
+
@Parameters(split = "\\+", splitSynopsisLabel = "+", paramLabel = "VALUE")
+lateinit var values: List<String>
@@ -9593,24 +9318,24 @@

14.9. C
Java
-
@Command(synopsisHeading = "", customSynopsis = {
-        "Usage: ln [OPTION]... [-T] TARGET LINK_NAME   (1st form)",
-        "  or:  ln [OPTION]... TARGET                  (2nd form)",
-        "  or:  ln [OPTION]... TARGET... DIRECTORY     (3rd form)",
-        "  or:  ln [OPTION]... -t DIRECTORY TARGET...  (4th form)",
-})
-class Ln { /* ... */ }
+
@Command(synopsisHeading = "", customSynopsis = {
+        "Usage: ln [OPTION]... [-T] TARGET LINK_NAME   (1st form)",
+        "  or:  ln [OPTION]... TARGET                  (2nd form)",
+        "  or:  ln [OPTION]... TARGET... DIRECTORY     (3rd form)",
+        "  or:  ln [OPTION]... -t DIRECTORY TARGET...  (4th form)",
+})
+class Ln { /* ... */ }
Kotlin
-
@Command(synopsisHeading = "", mixinStandardHelpOptions = true, customSynopsis = ["""
+
@Command(synopsisHeading = "", mixinStandardHelpOptions = true, customSynopsis = ["""
 Usage: ln [OPTION]... [-T] TARGET LINK_NAME   (1st form)
    or: ln [OPTION]... TARGET                  (2nd form)
    or: ln [OPTION]... TARGET... DIRECTORY     (3rd form)
-   or:  ln [OPTION]... -t DIRECTORY TARGET...  (4th form)"""])
-class Ln { /* ... */ }
+ or: ln [OPTION]... -t DIRECTORY TARGET... (4th form)"""]) +class Ln { /* ... */ }

@@ -9632,8 +9357,8 @@

-
@Command(name = "git", synopsisSubcommandLabel = "COMMAND")
-class Git { /* ... */ }
+
@Command(name = "git", synopsisSubcommandLabel = "COMMAND")
+class Git { /* ... */ }
Kotlin
-
@Command(name = "fs", synopsisSubcommandLabel = "(list | add | delete)",
-         subcommands = [List::class, Add::class, Delete::class],
-         mixinStandardHelpOptions = true)
-class Fs { /* ... */ }
+
@Command(name = "fs", synopsisSubcommandLabel = "(list | add | delete)",
+         subcommands = [List::class, Add::class, Delete::class],
+         mixinStandardHelpOptions = true)
+class Fs { /* ... */ }
@@ -9687,33 +9412,33 @@

14.12. Ex
Java
-
@Command(mixinStandardHelpOptions = true,
-         exitCodeListHeading = "Exit Codes:%n",
-         exitCodeList = {
-             " 0:Successful program execution",
-             "64:Usage error: user input for the command was incorrect, " +
-                     "e.g., the wrong number of arguments, a bad flag, " +
-                     "a bad syntax in a parameter, etc.",
-             "70:Internal software error: an exception occurred when invoking " +
-                     "the business logic of this command."})
-class App {}
-new CommandLine(new App()).usage(System.out);
+
@Command(mixinStandardHelpOptions = true,
+         exitCodeListHeading = "Exit Codes:%n",
+         exitCodeList = {
+             " 0:Successful program execution",
+             "64:Usage error: user input for the command was incorrect, " +
+                     "e.g., the wrong number of arguments, a bad flag, " +
+                     "a bad syntax in a parameter, etc.",
+             "70:Internal software error: an exception occurred when invoking " +
+                     "the business logic of this command."})
+class App {}
+new CommandLine(new App()).usage(System.out);
Kotlin
-
@Command(mixinStandardHelpOptions = true,
-         exitCodeListHeading = "Exit Codes:%n",
-         exitCodeList = [
-             " 0:Successful program execution",
-             "64:Usage error: user input for the command was incorrect,"  +
-                    "e.g., the wrong number of arguments, a bad flag, " +
-                    "a bad syntax in a parameter, etc.",
-             "70:Internal software error: an exception occurred when invoking " +
-                    "the business logic of this command."])
-class App {}
-fun main(args: Array<String>) : Unit = CommandLine(App()).usage(System.out)
+
@Command(mixinStandardHelpOptions = true,
+         exitCodeListHeading = "Exit Codes:%n",
+         exitCodeList = [
+             " 0:Successful program execution",
+             "64:Usage error: user input for the command was incorrect,"  +
+                    "e.g., the wrong number of arguments, a bad flag, " +
+                    "a bad syntax in a parameter, etc.",
+             "70:Internal software error: an exception occurred when invoking " +
+                    "the business logic of this command."])
+class App {}
+fun main(args: Array<String>) : Unit = CommandLine(App()).usage(System.out)
@@ -9768,33 +9493,33 @@

14.14
Java
-
@Command(name = "commit",
-         sortOptions = false,
-         headerHeading = "Usage:%n%n",
-         synopsisHeading = "%n",
-         descriptionHeading = "%nDescription:%n%n",
-         parameterListHeading = "%nParameters:%n",
-         optionListHeading = "%nOptions:%n",
-         header = "Record changes to the repository.",
-         description = "Stores the current contents of the index in a new commit " +
-                 "along with a log message from the user describing the changes.")
-class GitCommit { /* ... */ }
+
@Command(name = "commit",
+         sortOptions = false,
+         headerHeading = "Usage:%n%n",
+         synopsisHeading = "%n",
+         descriptionHeading = "%nDescription:%n%n",
+         parameterListHeading = "%nParameters:%n",
+         optionListHeading = "%nOptions:%n",
+         header = "Record changes to the repository.",
+         description = "Stores the current contents of the index in a new commit " +
+                 "along with a log message from the user describing the changes.")
+class GitCommit { /* ... */ }
Kotlin
-
@Command(name = "commit",
-         sortOptions = false,
-         headerHeading = "Usage:%n%n",
-         synopsisHeading = "%n",
-         descriptionHeading = "%nDescription:%n%n",
-         parameterListHeading = "%nParameters:%n",
-         optionListHeading = "%nOptions:%n",
-         header = ["Record changes to the repository."],
-         description = ["Stores the current contents of the index in a new commit " +
-                 "along with a log message from the user describing the changes."])
-class GitCommit { /* ... */ }
+
@Command(name = "commit",
+         sortOptions = false,
+         headerHeading = "Usage:%n%n",
+         synopsisHeading = "%n",
+         descriptionHeading = "%nDescription:%n%n",
+         parameterListHeading = "%nParameters:%n",
+         optionListHeading = "%nOptions:%n",
+         header = ["Record changes to the repository."],
+         description = ["Stores the current contents of the index in a new commit " +
+                 "along with a log message from the user describing the changes."])
+class GitCommit { /* ... */ }
Kotlin
-
@Command
-class App {
-    @Parameters(index = "0",    description = ["destination host"])
-    lateinit var host: InetAddress
-    @Parameters(index = "1",    description = ["destination port"])
-    var port = 0
-    @Parameters(index = "2..*", description = ["files to transfer"])
-    lateinit var files: Array<String>
-
-    @Parameters(hidden = true)
-    lateinit var all: Array<String>
-}
+
@Command
+class App {
+    @Parameters(index = "0",    description = ["destination host"])
+    lateinit var host: InetAddress
+    @Parameters(index = "1",    description = ["destination port"])
+    var port = 0
+    @Parameters(index = "2..*", description = ["files to transfer"])
+    lateinit var files: Array<String>
+
+    @Parameters(hidden = true)
+    lateinit var all: Array<String>
+}
@@ -9948,22 +9673,22 @@

14.18.1. Example
Java
-
@Command(name = "myapp", showAtFileInUsageHelp = true,
-         mixinStandardHelpOptions = true, description = "Example command.")
-class MyApp {
-    @Parameters(description = "A file.") File file;
-}
+
@Command(name = "myapp", showAtFileInUsageHelp = true,
+         mixinStandardHelpOptions = true, description = "Example command.")
+class MyApp {
+    @Parameters(description = "A file.") File file;
+}

Kotlin
-
@Command(name = "myapp", showAtFileInUsageHelp = true,
-         mixinStandardHelpOptions = true, description = ["Example command."])
-class MyApp {
-    @Parameters(description = ["A file."])
-    lateinit var file: File
-}
+
@Command(name = "myapp", showAtFileInUsageHelp = true,
+         mixinStandardHelpOptions = true, description = ["Example command."])
+class MyApp {
+    @Parameters(description = ["A file."])
+    lateinit var file: File
+}
Kotlin
-
import picocli.CommandLine.Model.UsageMessageSpec.SECTION_KEY_COMMAND_LIST_HEADING
-import picocli.CommandLine.Model.UsageMessageSpec.SECTION_KEY_AT_FILE_PARAMETER
-// ...
-
-@Command(name = "myapp", showAtFileInUsageHelp = true,
-         mixinStandardHelpOptions = true, description = ["Example command."])
-class MyApp {
-    @Parameters(description = ["A file."]) lateinit var file: File
-
-    companion object {
-        @JvmStatic
-        fun main(args: Array<String>) {
-            val cmd = CommandLine(MyApp())
-            val copy: MutableList<String> = ArrayList(cmd.helpSectionKeys)
-            copy.remove(SECTION_KEY_AT_FILE_PARAMETER)
-            copy.add(copy.indexOf(SECTION_KEY_COMMAND_LIST_HEADING), SECTION_KEY_AT_FILE_PARAMETER)
-            cmd.helpSectionKeys = copy
-            cmd.usage(System.out)
-        }
-    }
-}
+
import picocli.CommandLine.Model.UsageMessageSpec.SECTION_KEY_COMMAND_LIST_HEADING
+import picocli.CommandLine.Model.UsageMessageSpec.SECTION_KEY_AT_FILE_PARAMETER
+// ...
+
+@Command(name = "myapp", showAtFileInUsageHelp = true,
+         mixinStandardHelpOptions = true, description = ["Example command."])
+class MyApp {
+    @Parameters(description = ["A file."]) lateinit var file: File
+
+    companion object {
+        @JvmStatic
+        fun main(args: Array<String>) {
+            val cmd = CommandLine(MyApp())
+            val copy: MutableList<String> = ArrayList(cmd.helpSectionKeys)
+            copy.remove(SECTION_KEY_AT_FILE_PARAMETER)
+            copy.add(copy.indexOf(SECTION_KEY_COMMAND_LIST_HEADING), SECTION_KEY_AT_FILE_PARAMETER)
+            cmd.helpSectionKeys = copy
+            cmd.usage(System.out)
+        }
+    }
+}
@@ -10117,22 +9842,22 @@

14.19.1. Example
Java
-
@Command(name = "myapp", showEndOfOptionsDelimiterInUsageHelp = true,
-         mixinStandardHelpOptions = true, description = "Example command.")
-class MyApp {
-    @Parameters(description = "A file.") File file;
-}
+
@Command(name = "myapp", showEndOfOptionsDelimiterInUsageHelp = true,
+         mixinStandardHelpOptions = true, description = "Example command.")
+class MyApp {
+    @Parameters(description = "A file.") File file;
+}

Kotlin
-
@Command(name = "myapp", showEndOfOptionsDelimiterInUsageHelp = true,
-         mixinStandardHelpOptions = true, description = ["Example command."])
-class MyApp {
-    @Parameters(description = ["A file."])
-    lateinit var file: File
-}
+
@Command(name = "myapp", showEndOfOptionsDelimiterInUsageHelp = true,
+         mixinStandardHelpOptions = true, description = ["Example command."])
+class MyApp {
+    @Parameters(description = ["A file."])
+    lateinit var file: File
+}
Kotlin
-
import picocli.CommandLine.Model.UsageMessageSpec.SECTION_KEY_OPTION_LIST
-import picocli.CommandLine.Model.UsageMessageSpec.SECTION_KEY_END_OF_OPTIONS
-// ...
-
-@Command(name = "myapp", showEndOfOptionsDelimiterInUsageHelp = true,
-         mixinStandardHelpOptions = true, description = ["Example command."])
-class MyApp {
-    @Parameters(description = ["A file."])
-    lateinit var file: File
-
-    companion object {
-        @JvmStatic
-        fun main(args: Array<String>) {
-            val cmd = CommandLine(MyApp())
-            val copy: MutableList<String> = ArrayList(cmd.helpSectionKeys)
-            copy.remove(SECTION_KEY_END_OF_OPTIONS)
-            copy.add(copy.indexOf(SECTION_KEY_OPTION_LIST), SECTION_KEY_END_OF_OPTIONS)
-            cmd.helpSectionKeys = copy
-
-            cmd.usage(System.out)
-        }
-    }
-}
+
import picocli.CommandLine.Model.UsageMessageSpec.SECTION_KEY_OPTION_LIST
+import picocli.CommandLine.Model.UsageMessageSpec.SECTION_KEY_END_OF_OPTIONS
+// ...
+
+@Command(name = "myapp", showEndOfOptionsDelimiterInUsageHelp = true,
+         mixinStandardHelpOptions = true, description = ["Example command."])
+class MyApp {
+    @Parameters(description = ["A file."])
+    lateinit var file: File
+
+    companion object {
+        @JvmStatic
+        fun main(args: Array<String>) {
+            val cmd = CommandLine(MyApp())
+            val copy: MutableList<String> = ArrayList(cmd.helpSectionKeys)
+            copy.remove(SECTION_KEY_END_OF_OPTIONS)
+            copy.add(copy.indexOf(SECTION_KEY_OPTION_LIST), SECTION_KEY_END_OF_OPTIONS)
+            cmd.helpSectionKeys = copy
+
+            cmd.usage(System.out)
+        }
+    }
+}
Kotlin
-
class DefaultValues {
-    @Option(names = ["-f", "--file"], defaultValue = "config.xml",
-        description = ["the file to use (default: \${DEFAULT-VALUE})"])
-    lateinit var file: File
-}
+
class DefaultValues {
+    @Option(names = ["-f", "--file"], defaultValue = "config.xml",
+        description = ["the file to use (default: \${DEFAULT-VALUE})"])
+    lateinit var file: File
+}
 
-fun main(args: Array<String>) = CommandLine(DefaultValues()).usage(System.out)
+fun main(args: Array<String>) = CommandLine(DefaultValues()).usage(System.out)
Kotlin
-
enum class Lang { java, groovy, kotlin, javascript, frege, clojure }
+
enum class Lang { java, groovy, kotlin, javascript, frege, clojure }
 
-class MyAbcCandidates : ArrayList<String?>(listOf("A", "B", "C"))
+class MyAbcCandidates : ArrayList<String?>(listOf("A", "B", "C"))
 
-class ValidValuesDemo {
-    @Option(names = ["-l"], description = ["Enum values: \${COMPLETION-CANDIDATES}"])
-    lateinit var lang: Lang
+class ValidValuesDemo {
+    @Option(names = ["-l"], description = ["Enum values: \${COMPLETION-CANDIDATES}"])
+    lateinit var lang: Lang
 
-    @Option(names = ["-o"], completionCandidates = MyAbcCandidates::class,
-            description = ["Candidates: \${COMPLETION-CANDIDATES}"])
-    lateinit var option: String
-}
+    @Option(names = ["-o"], completionCandidates = MyAbcCandidates::class,
+            description = ["Candidates: \${COMPLETION-CANDIDATES}"])
+    lateinit var option: String
+}
 
-fun main(args: Array<String>) = CommandLine(ValidValuesDemo()).usage(System.out)
+fun main(args: Array<String>) = CommandLine(ValidValuesDemo()).usage(System.out)
Kotlin
-
@Command(description = ["Custom @|bold,underline styles|@ and @|fg(red) colors|@."])
+
@Command(description = ["Custom @|bold,underline styles|@ and @|fg(red) colors|@."])
Kotlin
-
@Command(name = "commit",
-        sortOptions = false,
-        headerHeading = "@|bold,underline Usage|@:%n%n",
-        synopsisHeading = "%n",
-        descriptionHeading = "%n@|bold,underline Description|@:%n%n",
-        parameterListHeading = "%n@|bold,underline Parameters|@:%n",
-        optionListHeading = "%n@|bold,underline Options|@:%n",
-        header = ["Record changes to the repository."],
-        description = ["Stores the current contents of the index in a new commit " +
-                "along with a log message from the user describing the changes."])
-class GitCommit { /* ... */ }
+
@Command(name = "commit",
+        sortOptions = false,
+        headerHeading = "@|bold,underline Usage|@:%n%n",
+        synopsisHeading = "%n",
+        descriptionHeading = "%n@|bold,underline Description|@:%n%n",
+        parameterListHeading = "%n@|bold,underline Parameters|@:%n",
+        optionListHeading = "%n@|bold,underline Options|@:%n",
+        header = ["Record changes to the repository."],
+        description = ["Stores the current contents of the index in a new commit " +
+                "along with a log message from the user describing the changes."])
+class GitCommit { /* ... */ }
Kotlin
-
import picocli.CommandLine.Help.Ansi;
-// ...
-val str: String = Ansi.AUTO.string("@|bold,green,underline Hello, colored world!|@")
-println(str)
+
import picocli.CommandLine.Help.Ansi;
+// ...
+val str: String = Ansi.AUTO.string("@|bold,green,underline Hello, colored world!|@")
+println(str)

@@ -10628,34 +10353,34 @@

15.5.1. Color
Java
-
// see also CommandLine.Help.defaultColorScheme()
-ColorScheme colorScheme = new ColorScheme.Builder()
-        .commands    (Style.bold, Style.underline)    // combine multiple styles
-        .options     (Style.fg_yellow)                // yellow foreground color
-        .parameters  (Style.fg_yellow)
-        .optionParams(Style.italic)
-        .errors      (Style.fg_red, Style.bold)
-        .stackTraces (Style.italic)
-        .build();
+
// see also CommandLine.Help.defaultColorScheme()
+ColorScheme colorScheme = new ColorScheme.Builder()
+        .commands    (Style.bold, Style.underline)    // combine multiple styles
+        .options     (Style.fg_yellow)                // yellow foreground color
+        .parameters  (Style.fg_yellow)
+        .optionParams(Style.italic)
+        .errors      (Style.fg_red, Style.bold)
+        .stackTraces (Style.italic)
+        .build();
 
-CommandLine.usage(annotatedObject, System.out, colorScheme);
-// ...
+CommandLine.usage(annotatedObject, System.out, colorScheme); +// ...
Kotlin
-
// see also CommandLine.Help.defaultColorScheme()
-val colorScheme: Help.ColorScheme = ColorScheme.Builder()
-        .commands    (Style.bold, Style.underline)    // combine multiple styles
-        .options     (Style.fg_yellow)                // yellow foreground color
-        .parameters  (Style.fg_yellow)
-        .optionParams(Style.italic)
-        .errors      (Style.fg_red, Style.bold)
-        .stackTraces (Style.italic)
-        .build()
+
// see also CommandLine.Help.defaultColorScheme()
+val colorScheme: Help.ColorScheme = ColorScheme.Builder()
+        .commands    (Style.bold, Style.underline)    // combine multiple styles
+        .options     (Style.fg_yellow)                // yellow foreground color
+        .parameters  (Style.fg_yellow)
+        .optionParams(Style.italic)
+        .errors      (Style.fg_red, Style.bold)
+        .stackTraces (Style.italic)
+        .build()
 
-CommandLine.usage(annotatedObject, System.out, colorScheme)
+CommandLine.usage(annotatedObject, System.out, colorScheme)
@@ -10664,25 +10389,25 @@

15.5.1. Color
Java
-
public static void main(String[] args) {
-    ColorScheme colorScheme = createColorScheme();
+
public static void main(String[] args) {
+    ColorScheme colorScheme = createColorScheme();
 
-    new CommandLine(new MyApp())
-            .setColorScheme(colorScheme) // use this color scheme in the usage help message
-            .execute(args);
-}
+ new CommandLine(new MyApp()) + .setColorScheme(colorScheme) // use this color scheme in the usage help message + .execute(args); +}
Kotlin
-
fun main(args: Array<String>) {
-    val colorScheme: ColorScheme = createColorScheme()
+
fun main(args: Array<String>) {
+    val colorScheme: ColorScheme = createColorScheme()
 
-    CommandLine(MyApp())
-            .setColorScheme(colorScheme) // use this color scheme in the usage help message
-            .execute(*args)
-}
+ CommandLine(MyApp()) + .setColorScheme(colorScheme) // use this color scheme in the usage help message + .execute(*args) +}

@@ -10757,25 +10482,25 @@

Jansi
Java
-
import org.fusesource.jansi.AnsiConsole;
-// ...
-public static void main(String[] args) {
-    AnsiConsole.systemInstall(); // enable colors on Windows
-    new CommandLine(new WindowsJansiDemo()).execute(args);
-    AnsiConsole.systemUninstall(); // cleanup when done
-}
+
import org.fusesource.jansi.AnsiConsole;
+// ...
+public static void main(String[] args) {
+    AnsiConsole.systemInstall(); // enable colors on Windows
+    new CommandLine(new WindowsJansiDemo()).execute(args);
+    AnsiConsole.systemUninstall(); // cleanup when done
+}
Kotlin
-
import org.fusesource.jansi.AnsiConsole;
-// ...
-fun main(args: Array<String>) {
-    AnsiConsole.systemInstall() // enable colors on Windows
-    CommandLine(WindowsJansiDemo()).execute(*args)
-    AnsiConsole.systemUninstall() // cleanup when done
-}
+
import org.fusesource.jansi.AnsiConsole;
+// ...
+fun main(args: Array<String>) {
+    AnsiConsole.systemInstall() // enable colors on Windows
+    CommandLine(WindowsJansiDemo()).execute(*args)
+    AnsiConsole.systemUninstall() // cleanup when done
+}

@@ -10791,28 +10516,28 @@

Java
-
import picocli.jansi.graalvm.AnsiConsole; // not org.fusesource.jansi.AnsiConsole
-// ...
-public static void main(String[] args) {
-    int exitCode;
-    try (AnsiConsole ansi = AnsiConsole.windowsInstall()) {
-        exitCode = new CommandLine(new MyApp()).execute(args);
-    }
-    System.exit(exitCode);
-}
+
import picocli.jansi.graalvm.AnsiConsole; // not org.fusesource.jansi.AnsiConsole
+// ...
+public static void main(String[] args) {
+    int exitCode;
+    try (AnsiConsole ansi = AnsiConsole.windowsInstall()) {
+        exitCode = new CommandLine(new MyApp()).execute(args);
+    }
+    System.exit(exitCode);
+}
Kotlin
-
import picocli.jansi.graalvm.AnsiConsole // not org.fusesource.jansi.AnsiConsole
-// ...
-fun main(args: Array<String>) {
-    val exitCode: Int
-    AnsiConsole.windowsInstall().use
-        { exitCode = CommandLine(MyApp()).execute(*args) }
-    System.exit(exitCode)
-}
+
import picocli.jansi.graalvm.AnsiConsole // not org.fusesource.jansi.AnsiConsole
+// ...
+fun main(args: Array<String>) {
+    val exitCode: Int
+    AnsiConsole.windowsInstall().use
+        { exitCode = CommandLine(MyApp()).execute(*args) }
+    System.exit(exitCode)
+}
@@ -10894,19 +10619,19 @@

1
Java
-
import picocli.CommandLine.Help.Ansi;
+
import picocli.CommandLine.Help.Ansi;
 
-// print usage help message to STDOUT without ANSI escape codes
-CommandLine.usage(new App(), System.out, Ansi.OFF);
+// print usage help message to STDOUT without ANSI escape codes +CommandLine.usage(new App(), System.out, Ansi.OFF);
Kotlin
-
import picocli.CommandLine.Help.Ansi
+
import picocli.CommandLine.Help.Ansi
 
-// print usage help message to STDOUT without ANSI escape codes
-CommandLine.usage(App(), System.out, Ansi.OFF)
+// print usage help message to STDOUT without ANSI escape codes +CommandLine.usage(App(), System.out, Ansi.OFF)
@@ -10986,111 +10711,111 @@

Java
-
import static picocli.CommandLine.Model.UsageMessageSpec.*;
-// ...
+
import static picocli.CommandLine.Model.UsageMessageSpec.*;
+// ...
 
-// The default section renderers delegate to methods in Help for their implementation
-// (using Java 8 lambda notation for brevity):
-Map<String, IHelpSectionRenderer> map = new HashMap<>();
-map.put(SECTION_KEY_HEADER_HEADING,         help -> help.headerHeading());
-map.put(SECTION_KEY_HEADER,                 help -> help.header());
+// The default section renderers delegate to methods in Help for their implementation
+// (using Java 8 lambda notation for brevity):
+Map<String, IHelpSectionRenderer> map = new HashMap<>();
+map.put(SECTION_KEY_HEADER_HEADING,         help -> help.headerHeading());
+map.put(SECTION_KEY_HEADER,                 help -> help.header());
 
-//e.g. Usage:
-map.put(SECTION_KEY_SYNOPSIS_HEADING,       help -> help.synopsisHeading());
+//e.g. Usage:
+map.put(SECTION_KEY_SYNOPSIS_HEADING,       help -> help.synopsisHeading());
 
-//e.g. <cmd> [OPTIONS] <subcmd> [COMMAND-OPTIONS] [ARGUMENTS]
-map.put(SECTION_KEY_SYNOPSIS,               help -> help.synopsis(help.synopsisHeadingLength()));
+//e.g. <cmd> [OPTIONS] <subcmd> [COMMAND-OPTIONS] [ARGUMENTS]
+map.put(SECTION_KEY_SYNOPSIS,               help -> help.synopsis(help.synopsisHeadingLength()));
 
-//e.g. %nDescription:%n%n
-map.put(SECTION_KEY_DESCRIPTION_HEADING,    help -> help.descriptionHeading());
+//e.g. %nDescription:%n%n
+map.put(SECTION_KEY_DESCRIPTION_HEADING,    help -> help.descriptionHeading());
 
-//e.g. {"Converts foos to bars.", "Use options to control conversion mode."}
-map.put(SECTION_KEY_DESCRIPTION,            help -> help.description());
+//e.g. {"Converts foos to bars.", "Use options to control conversion mode."}
+map.put(SECTION_KEY_DESCRIPTION,            help -> help.description());
 
-//e.g. %nPositional parameters:%n%n
-map.put(SECTION_KEY_PARAMETER_LIST_HEADING, help -> help.parameterListHeading());
+//e.g. %nPositional parameters:%n%n
+map.put(SECTION_KEY_PARAMETER_LIST_HEADING, help -> help.parameterListHeading());
 
-//e.g. [FILE...] the files to convert
-map.put(SECTION_KEY_PARAMETER_LIST,         help -> help.parameterList());
+//e.g. [FILE...] the files to convert
+map.put(SECTION_KEY_PARAMETER_LIST,         help -> help.parameterList());
 
-//e.g. %nOptions:%n%n
-map.put(SECTION_KEY_OPTION_LIST_HEADING,    help -> help.optionListHeading());
+//e.g. %nOptions:%n%n
+map.put(SECTION_KEY_OPTION_LIST_HEADING,    help -> help.optionListHeading());
 
-//e.g. -h, --help   displays this help and exits
-map.put(SECTION_KEY_OPTION_LIST,            help -> help.optionList());
+//e.g. -h, --help   displays this help and exits
+map.put(SECTION_KEY_OPTION_LIST,            help -> help.optionList());
 
-//e.g. %nCommands:%n%n
-map.put(SECTION_KEY_COMMAND_LIST_HEADING,   help -> help.commandListHeading());
+//e.g. %nCommands:%n%n
+map.put(SECTION_KEY_COMMAND_LIST_HEADING,   help -> help.commandListHeading());
 
-//e.g.    add       this command adds the frup to the frooble
-map.put(SECTION_KEY_COMMAND_LIST,           help -> help.commandList());
-map.put(SECTION_KEY_EXIT_CODE_LIST_HEADING, help -> help.exitCodeListHeading());
-map.put(SECTION_KEY_EXIT_CODE_LIST,         help -> help.exitCodeList());
-map.put(SECTION_KEY_FOOTER_HEADING,         help -> help.footerHeading());
-map.put(SECTION_KEY_FOOTER,                 help -> help.footer());
+//e.g. add this command adds the frup to the frooble +map.put(SECTION_KEY_COMMAND_LIST, help -> help.commandList()); +map.put(SECTION_KEY_EXIT_CODE_LIST_HEADING, help -> help.exitCodeListHeading()); +map.put(SECTION_KEY_EXIT_CODE_LIST, help -> help.exitCodeList()); +map.put(SECTION_KEY_FOOTER_HEADING, help -> help.footerHeading()); +map.put(SECTION_KEY_FOOTER, help -> help.footer());
Kotlin
-
import picocli.CommandLine.Model.UsageMessageSpec.*
-// ...
+
import picocli.CommandLine.Model.UsageMessageSpec.*
+// ...
 
-// The default section renderers delegate to methods in Help for their implementation
-// (using lambda expressions for brevity):
-val map: MutableMap<String, IHelpSectionRenderer> = HashMap()
-map[SECTION_KEY_HEADER_HEADING] =
-    IHelpSectionRenderer { help: Help -> help.headerHeading() }
-map[SECTION_KEY_HEADER] =
-    IHelpSectionRenderer { help: Help -> help.header() }
+// The default section renderers delegate to methods in Help for their implementation
+// (using lambda expressions for brevity):
+val map: MutableMap<String, IHelpSectionRenderer> = HashMap()
+map[SECTION_KEY_HEADER_HEADING] =
+    IHelpSectionRenderer { help: Help -> help.headerHeading() }
+map[SECTION_KEY_HEADER] =
+    IHelpSectionRenderer { help: Help -> help.header() }
 
-//e.g. Usage:
-map[SECTION_KEY_SYNOPSIS_HEADING] =
-    IHelpSectionRenderer { help: Help -> help.synopsisHeading() }
+//e.g. Usage:
+map[SECTION_KEY_SYNOPSIS_HEADING] =
+    IHelpSectionRenderer { help: Help -> help.synopsisHeading() }
 
-//e.g. <cmd> [OPTIONS] <subcmd> [COMMAND-OPTIONS] [ARGUMENTS]
-map[SECTION_KEY_SYNOPSIS] =
-    IHelpSectionRenderer { help: Help -> help.synopsis(help.synopsisHeadingLength()) }
+//e.g. <cmd> [OPTIONS] <subcmd> [COMMAND-OPTIONS] [ARGUMENTS]
+map[SECTION_KEY_SYNOPSIS] =
+    IHelpSectionRenderer { help: Help -> help.synopsis(help.synopsisHeadingLength()) }
 
-//e.g. %nDescription:%n%n
-map[SECTION_KEY_DESCRIPTION_HEADING] =
-    IHelpSectionRenderer { help: Help -> help.descriptionHeading() }
+//e.g. %nDescription:%n%n
+map[SECTION_KEY_DESCRIPTION_HEADING] =
+    IHelpSectionRenderer { help: Help -> help.descriptionHeading() }
 
-//e.g. {"Converts foos to bars.", "Use options to control conversion mode."}
-map[SECTION_KEY_DESCRIPTION] =
-    IHelpSectionRenderer  { help: Help -> help.description() }
+//e.g. {"Converts foos to bars.", "Use options to control conversion mode."}
+map[SECTION_KEY_DESCRIPTION] =
+    IHelpSectionRenderer  { help: Help -> help.description() }
 
-//e.g. %nPositional parameters:%n%n
-map[SECTION_KEY_PARAMETER_LIST_HEADING] =
-    IHelpSectionRenderer { help: Help -> help.parameterListHeading() }
+//e.g. %nPositional parameters:%n%n
+map[SECTION_KEY_PARAMETER_LIST_HEADING] =
+    IHelpSectionRenderer { help: Help -> help.parameterListHeading() }
 
-//e.g. [FILE...] the files to convert
-map[SECTION_KEY_PARAMETER_LIST] =
-    IHelpSectionRenderer { help: Help -> help.parameterList() }
+//e.g. [FILE...] the files to convert
+map[SECTION_KEY_PARAMETER_LIST] =
+    IHelpSectionRenderer { help: Help -> help.parameterList() }
 
-//e.g. %nOptions:%n%n
-map[SECTION_KEY_OPTION_LIST_HEADING] =
-    IHelpSectionRenderer { help: Help -> help.optionListHeading() }
+//e.g. %nOptions:%n%n
+map[SECTION_KEY_OPTION_LIST_HEADING] =
+    IHelpSectionRenderer { help: Help -> help.optionListHeading() }
 
-//e.g. -h, --help   displays this help and exits
-map[SECTION_KEY_OPTION_LIST] =
-    IHelpSectionRenderer { help: Help -> help.optionList() }
+//e.g. -h, --help   displays this help and exits
+map[SECTION_KEY_OPTION_LIST] =
+    IHelpSectionRenderer { help: Help -> help.optionList() }
 
-//e.g. %nCommands:%n%n
-map[SECTION_KEY_COMMAND_LIST_HEADING] =
-    IHelpSectionRenderer { help: Help -> help.commandListHeading() }
+//e.g. %nCommands:%n%n
+map[SECTION_KEY_COMMAND_LIST_HEADING] =
+    IHelpSectionRenderer { help: Help -> help.commandListHeading() }
 
-//e.g.    add       this command adds the frup to the frooble
-map[SECTION_KEY_COMMAND_LIST] =
-    IHelpSectionRenderer { help: Help -> help.commandList() }
-map[SECTION_KEY_EXIT_CODE_LIST_HEADING] =
-    IHelpSectionRenderer { help: Help -> help.exitCodeListHeading() }
-map[SECTION_KEY_EXIT_CODE_LIST] =
-    IHelpSectionRenderer { help: Help -> help.exitCodeList() }
-map[SECTION_KEY_FOOTER_HEADING] =
-    IHelpSectionRenderer { help: Help -> help.footerHeading() }
-map[SECTION_KEY_FOOTER] =
-    IHelpSectionRenderer { help: Help -> help.footer() }
+//e.g. add this command adds the frup to the frooble +map[SECTION_KEY_COMMAND_LIST] = + IHelpSectionRenderer { help: Help -> help.commandList() } +map[SECTION_KEY_EXIT_CODE_LIST_HEADING] = + IHelpSectionRenderer { help: Help -> help.exitCodeListHeading() } +map[SECTION_KEY_EXIT_CODE_LIST] = + IHelpSectionRenderer { help: Help -> help.exitCodeList() } +map[SECTION_KEY_FOOTER_HEADING] = + IHelpSectionRenderer { help: Help -> help.footerHeading() } +map[SECTION_KEY_FOOTER] = + IHelpSectionRenderer { help: Help -> help.footer() }
@@ -11162,59 +10887,59 @@

Java
-
// help section keys
-final String SECTION_KEY_ENV_HEADING = "environmentVariablesHeading";
-final String SECTION_KEY_ENV_DETAILS = "environmentVariables";
-// ...
+
// help section keys
+final String SECTION_KEY_ENV_HEADING = "environmentVariablesHeading";
+final String SECTION_KEY_ENV_DETAILS = "environmentVariables";
+// ...
 
-// the data to display
-Map<String, String> env = new LinkedHashMap<>();
-env.put("FOO", "explanation of foo");
-env.put("BAR", "explanation of bar");
-env.put("XYZ", "xxxx yyyy zzz");
+// the data to display
+Map<String, String> env = new LinkedHashMap<>();
+env.put("FOO", "explanation of foo");
+env.put("BAR", "explanation of bar");
+env.put("XYZ", "xxxx yyyy zzz");
 
-// register the custom section renderers
-CommandLine cmd = new CommandLine(new MyApp());
-cmd.getHelpSectionMap().put(SECTION_KEY_ENV_HEADING,
-                            help -> help.createHeading("Environment Variables:%n"));
-cmd.getHelpSectionMap().put(SECTION_KEY_ENV_DETAILS,
-                            help -> help.createTextTable(env).toString());
+// register the custom section renderers
+CommandLine cmd = new CommandLine(new MyApp());
+cmd.getHelpSectionMap().put(SECTION_KEY_ENV_HEADING,
+                            help -> help.createHeading("Environment Variables:%n"));
+cmd.getHelpSectionMap().put(SECTION_KEY_ENV_DETAILS,
+                            help -> help.createTextTable(env).toString());
 
-// specify the location of the new sections
-List<String> keys = new ArrayList<>(cmd.getHelpSectionKeys());
-int index = keys.indexOf(CommandLine.Model.UsageMessageSpec.SECTION_KEY_FOOTER_HEADING);
-keys.add(index, SECTION_KEY_ENV_HEADING);
-keys.add(index + 1, SECTION_KEY_ENV_DETAILS);
-cmd.setHelpSectionKeys(keys);
+// specify the location of the new sections +List<String> keys = new ArrayList<>(cmd.getHelpSectionKeys()); +int index = keys.indexOf(CommandLine.Model.UsageMessageSpec.SECTION_KEY_FOOTER_HEADING); +keys.add(index, SECTION_KEY_ENV_HEADING); +keys.add(index + 1, SECTION_KEY_ENV_DETAILS); +cmd.setHelpSectionKeys(keys);

Kotlin
-
// help section keys
-val SECTION_KEY_ENV_HEADING = "environmentVariablesHeading"
-val SECTION_KEY_ENV_DETAILS = "environmentVariables"
-// ...
+
// help section keys
+val SECTION_KEY_ENV_HEADING = "environmentVariablesHeading"
+val SECTION_KEY_ENV_DETAILS = "environmentVariables"
+// ...
 
-// the data to display
-val env: MutableMap<String, String> = LinkedHashMap()
-env["FOO"] = "explanation of foo"
-env["BAR"] = "explanation of bar"
-env["XYZ"] = "xxxx yyyy zzz"
+// the data to display
+val env: MutableMap<String, String> = LinkedHashMap()
+env["FOO"] = "explanation of foo"
+env["BAR"] = "explanation of bar"
+env["XYZ"] = "xxxx yyyy zzz"
 
-// register the custom section renderers
-val cmd = CommandLine(MyApp())
-cmd.helpSectionMap[SECTION_KEY_ENV_HEADING] =
-    IHelpSectionRenderer { help: Help -> help.createHeading("Environment Variables:%n") }
-cmd.helpSectionMap[SECTION_KEY_ENV_DETAILS] =
-    IHelpSectionRenderer { help: Help -> help.createTextTable(env).toString() }
+// register the custom section renderers
+val cmd = CommandLine(MyApp())
+cmd.helpSectionMap[SECTION_KEY_ENV_HEADING] =
+    IHelpSectionRenderer { help: Help -> help.createHeading("Environment Variables:%n") }
+cmd.helpSectionMap[SECTION_KEY_ENV_DETAILS] =
+    IHelpSectionRenderer { help: Help -> help.createTextTable(env).toString() }
 
-// specify the location of the new sections
-val keys = ArrayList(cmd.helpSectionKeys)
-val index = keys.indexOf(SECTION_KEY_FOOTER_HEADING)
-keys.add(index, SECTION_KEY_ENV_HEADING)
-keys.add(index + 1, SECTION_KEY_ENV_DETAILS)
-cmd.helpSectionKeys = keys
+// specify the location of the new sections +val keys = ArrayList(cmd.helpSectionKeys) +val index = keys.indexOf(SECTION_KEY_FOOTER_HEADING) +keys.add(index, SECTION_KEY_ENV_HEADING) +keys.add(index + 1, SECTION_KEY_ENV_DETAILS) +cmd.helpSectionKeys = keys
@@ -11230,13 +10955,13 @@

16.2. Custo
Java
-
CommandLine.usage(new ZipHelpDemo(), System.out);
+
CommandLine.usage(new ZipHelpDemo(), System.out);
Kotlin
-
CommandLine.usage(ZipHelpDemo(), System.out)
+
CommandLine.usage(ZipHelpDemo(), System.out)
Groovy
-
@Command(subcommands = [
-    GitStatus.class,
-    GitCommit.class,
-    GitAdd.class,
-    GitBranch.class,
-    GitCheckout.class,
-    GitClone.class,
-    GitDiff.class,
-    GitMerge.class,
-    GitPush.class,
-    GitRebase.class,
-    GitTag.class
-])
-public class Git { /* ... */ }
+
@Command(subcommands = [
+    GitStatus.class,
+    GitCommit.class,
+    GitAdd.class,
+    GitBranch.class,
+    GitCheckout.class,
+    GitClone.class,
+    GitDiff.class,
+    GitMerge.class,
+    GitPush.class,
+    GitRebase.class,
+    GitTag.class
+])
+public class Git { /* ... */ }
Kotlin
-
@Command(subcommands = [
-    GitStatus::class,
-    GitCommit::class,
-    GitAdd::class,
-    GitBranch::class,
-    GitCheckout::class,
-    GitClone::class,
-    GitDiff::class,
-    GitMerge::class,
-    GitPush::class,
-    GitRebase::class,
-    GitTag::class]
-)
-public class Git { /* ... */ }
+
@Command(subcommands = [
+    GitStatus::class,
+    GitCommit::class,
+    GitAdd::class,
+    GitBranch::class,
+    GitCheckout::class,
+    GitClone::class,
+    GitDiff::class,
+    GitMerge::class,
+    GitPush::class,
+    GitRebase::class,
+    GitTag::class]
+)
+public class Git { /* ... */ }
Scala
-
@Command(subcommands = Array(
-    classOf[GitStatus],
-    classOf[GitCommit],
-    classOf[GitAdd],
-    classOf[GitBranch],
-    classOf[GitCheckout],
-    classOf[GitClone],
-    classOf[GitDiff],
-    classOf[GitMerge],
-    classOf[GitPush],
-    classOf[GitRebase],
-    classOf[GitTag]
-))
-class Git { /* ... */ }
+
@Command(subcommands = Array(
+    classOf[GitStatus],
+    classOf[GitCommit],
+    classOf[GitAdd],
+    classOf[GitBranch],
+    classOf[GitCheckout],
+    classOf[GitClone],
+    classOf[GitDiff],
+    classOf[GitMerge],
+    classOf[GitPush],
+    classOf[GitRebase],
+    classOf[GitTag]
+))
+class Git { /* ... */ }
Groovy
-
def commandLine = new CommandLine(new Git())
-        .addSubcommand("status",   new GitStatus())
-        .addSubcommand("commit",   new GitCommit())
-        .addSubcommand("add",      new GitAdd())
-        .addSubcommand("branch",   new GitBranch())
-        .addSubcommand("checkout", new GitCheckout())
-        .addSubcommand("clone",    new GitClone())
-        .addSubcommand("diff",     new GitDiff())
-        .addSubcommand("merge",    new GitMerge())
-        .addSubcommand("push",     new GitPush())
-        .addSubcommand("rebase",   new GitRebase())
-        .addSubcommand("tag",      new GitTag());
+
def commandLine = new CommandLine(new Git())
+        .addSubcommand("status",   new GitStatus())
+        .addSubcommand("commit",   new GitCommit())
+        .addSubcommand("add",      new GitAdd())
+        .addSubcommand("branch",   new GitBranch())
+        .addSubcommand("checkout", new GitCheckout())
+        .addSubcommand("clone",    new GitClone())
+        .addSubcommand("diff",     new GitDiff())
+        .addSubcommand("merge",    new GitMerge())
+        .addSubcommand("push",     new GitPush())
+        .addSubcommand("rebase",   new GitRebase())
+        .addSubcommand("tag",      new GitTag());
Kotlin
-
val commandLine = CommandLine(Git())
-        .addSubcommand("status",   GitStatus())
-        .addSubcommand("commit",   GitCommit())
-        .addSubcommand("add",      GitAdd())
-        .addSubcommand("branch",   GitBranch())
-        .addSubcommand("checkout", GitCheckout())
-        .addSubcommand("clone",    GitClone())
-        .addSubcommand("diff",     GitDiff())
-        .addSubcommand("merge",    GitMerge())
-        .addSubcommand("push",     GitPush())
-        .addSubcommand("rebase",   GitRebase())
-        .addSubcommand("tag",      GitTag())
+
val commandLine = CommandLine(Git())
+        .addSubcommand("status",   GitStatus())
+        .addSubcommand("commit",   GitCommit())
+        .addSubcommand("add",      GitAdd())
+        .addSubcommand("branch",   GitBranch())
+        .addSubcommand("checkout", GitCheckout())
+        .addSubcommand("clone",    GitClone())
+        .addSubcommand("diff",     GitDiff())
+        .addSubcommand("merge",    GitMerge())
+        .addSubcommand("push",     GitPush())
+        .addSubcommand("rebase",   GitRebase())
+        .addSubcommand("tag",      GitTag())
Scala
-
val commandLine: CommandLine  = new CommandLine(new Git())
-        .addSubcommand("status",   new GitStatus())
-        .addSubcommand("commit",   new GitCommit())
-        .addSubcommand("add",      new GitAdd())
-        .addSubcommand("branch",   new GitBranch())
-        .addSubcommand("checkout", new GitCheckout())
-        .addSubcommand("clone",    new GitClone())
-        .addSubcommand("diff",     new GitDiff())
-        .addSubcommand("merge",    new GitMerge())
-        .addSubcommand("push",     new GitPush())
-        .addSubcommand("rebase",   new GitRebase())
-        .addSubcommand("tag",      new GitTag())
+
val commandLine: CommandLine  = new CommandLine(new Git())
+        .addSubcommand("status",   new GitStatus())
+        .addSubcommand("commit",   new GitCommit())
+        .addSubcommand("add",      new GitAdd())
+        .addSubcommand("branch",   new GitBranch())
+        .addSubcommand("checkout", new GitCheckout())
+        .addSubcommand("clone",    new GitClone())
+        .addSubcommand("diff",     new GitDiff())
+        .addSubcommand("merge",    new GitMerge())
+        .addSubcommand("push",     new GitPush())
+        .addSubcommand("rebase",   new GitRebase())
+        .addSubcommand("tag",      new GitTag())
@@ -11523,145 +11248,145 @@

Java
-
@Command(name = "foo", subcommands = Bar.class)
-class Foo implements Callable<Integer> {
-    @Option(names = "-x") int x;
+
@Command(name = "foo", subcommands = Bar.class)
+class Foo implements Callable<Integer> {
+    @Option(names = "-x") int x;
 
-    @Override public Integer call() {
-        System.out.printf("hi from foo, x=%d%n", x);
-        boolean ok = true;
-        return ok ? 0 : 1; // exit code
-    }
+    @Override public Integer call() {
+        System.out.printf("hi from foo, x=%d%n", x);
+        boolean ok = true;
+        return ok ? 0 : 1; // exit code
+    }
 
-    public static void main(String... args) {
-        int exitCode = new CommandLine(new Foo()).execute(args);
-        System.exit(exitCode);
-    }
-}
+    public static void main(String... args) {
+        int exitCode = new CommandLine(new Foo()).execute(args);
+        System.exit(exitCode);
+    }
+}
 
-@Command(name = "bar", description = "I'm a subcommand of `foo`")
-class Bar implements Callable<Integer> {
-    @Option(names = "-y") int y;
+@Command(name = "bar", description = "I'm a subcommand of `foo`")
+class Bar implements Callable<Integer> {
+    @Option(names = "-y") int y;
 
-    @Override public Integer call() {
-        System.out.printf("hi from bar, y=%d%n", y);
-        return 23;
-    }
+    @Override public Integer call() {
+        System.out.printf("hi from bar, y=%d%n", y);
+        return 23;
+    }
 
-    @Command(name = "baz", description = "I'm a subcommand of `bar`")
-    int baz(@Option(names = "-z") int z) {
-        System.out.printf("hi from baz, z=%d%n", z);
-        return 45;
-    }
-}
+ @Command(name = "baz", description = "I'm a subcommand of `bar`") + int baz(@Option(names = "-z") int z) { + System.out.printf("hi from baz, z=%d%n", z); + return 45; + } +}

Groovy
-
@Command(name = "foo", subcommands = Bar.class)
-class Foo implements Callable<Integer> {
-    @Option(names = "-x") def x
+
@Command(name = "foo", subcommands = Bar.class)
+class Foo implements Callable<Integer> {
+    @Option(names = "-x") def x
 
-    @Override public Integer call() {
-        println "hi from foo, x=$x"
-        def ok = true;
-        return ok ? 0 : 1 // exit code
-    }
+    @Override public Integer call() {
+        println "hi from foo, x=$x"
+        def ok = true;
+        return ok ? 0 : 1 // exit code
+    }
 
-    public static void main(String... args) {
-        def exitCode = new CommandLine(new Foo()).execute(args)
-        System.exit(exitCode)
-    }
-}
+    public static void main(String... args) {
+        def exitCode = new CommandLine(new Foo()).execute(args)
+        System.exit(exitCode)
+    }
+}
 
-@Command(name = "bar", description = "I'm a subcommand of `foo`")
-class Bar implements Callable<Integer> {
-    @Option(names = "-y") int y
+@Command(name = "bar", description = "I'm a subcommand of `foo`")
+class Bar implements Callable<Integer> {
+    @Option(names = "-y") int y
 
-    @Override public Integer call() {
-        println "hi from bar, y=$y"
-        return 23
-    }
+    @Override public Integer call() {
+        println "hi from bar, y=$y"
+        return 23
+    }
 
-    @Command(name = "baz", description = "I'm a subcommand of `bar`")
-    int baz(@Option(names = "-z") int z) {
-        println "hi from baz, z=$z"
-        return 45
-    }
-}
+ @Command(name = "baz", description = "I'm a subcommand of `bar`") + int baz(@Option(names = "-z") int z) { + println "hi from baz, z=$z" + return 45 + } +}
Kotlin
-
@Command(name = "foo", subcommands = [Bar::class])
-class Foo : Callable<Int> {
-    @Option(names = ["-x"]) var x: Int = 0
+
@Command(name = "foo", subcommands = [Bar::class])
+class Foo : Callable<Int> {
+    @Option(names = ["-x"]) var x: Int = 0
 
-    override fun call(): Int {
-        println("hi from foo, x=$x")
-        var ok: Boolean = true
-        return if (ok) 0 else 1 // exit code
-    }
-}
+    override fun call(): Int {
+        println("hi from foo, x=$x")
+        var ok: Boolean = true
+        return if (ok) 0 else 1 // exit code
+    }
+}
 
-fun main(args: Array<String>) : Unit = exitProcess(CommandLine(Foo()).execute(*args))
+fun main(args: Array<String>) : Unit = exitProcess(CommandLine(Foo()).execute(*args))
 
-@Command(name = "bar", description = ["I'm a subcommand of `foo`"])
-class Bar : Callable<Int> {
-    @Option(names = ["-y"]) var y: Int = 0
+@Command(name = "bar", description = ["I'm a subcommand of `foo`"])
+class Bar : Callable<Int> {
+    @Option(names = ["-y"]) var y: Int = 0
 
-    override fun call(): Int {
-        println("hi form bar, y=$y")
-        return 23
-    }
+    override fun call(): Int {
+        println("hi form bar, y=$y")
+        return 23
+    }
 
-    @Command(name = "baz", description = ["I'm a subcommand of `bar`"])
-    fun baz( @Option(names = ["-z"]) z: Int) : Int {
-        println("hi from baz, z=$z")
-        return 45
-    }
-}
+ @Command(name = "baz", description = ["I'm a subcommand of `bar`"]) + fun baz( @Option(names = ["-z"]) z: Int) : Int { + println("hi from baz, z=$z") + return 45 + } +}
Scala
-
@Command(name = "foo", subcommands = Array(classOf[Bar]))
-class Foo extends Callable[Integer] {
-    @Option(names = Array("-x"))
-    var x = 0
+
@Command(name = "foo", subcommands = Array(classOf[Bar]))
+class Foo extends Callable[Integer] {
+    @Option(names = Array("-x"))
+    var x = 0
 
-    override def call: Integer = {
-        println(s"hi from foo, $x")
-        val ok = true
-        if (ok) 0 else 1 // exit code
-    }
-}
+    override def call: Integer = {
+        println(s"hi from foo, $x")
+        val ok = true
+        if (ok) 0 else 1 // exit code
+    }
+}
 
-object Foo{
-    def main(args: Array[String]): Unit = {
-        val exitCode : Int = new CommandLine(new Foo()).execute(args: _*)
-        System.exit(exitCode)
-    }
-}
+object Foo{
+    def main(args: Array[String]): Unit = {
+        val exitCode : Int = new CommandLine(new Foo()).execute(args: _*)
+        System.exit(exitCode)
+    }
+}
 
-@Command(name = "bar", description = Array("I'm a subcommand of `foo`")) class Bar extends Callable[Integer] {
-    @Option(names = Array("-y"))
-    var y = 0
+@Command(name = "bar", description = Array("I'm a subcommand of `foo`")) class Bar extends Callable[Integer] {
+    @Option(names = Array("-y"))
+    var y = 0
 
-    override def call: Integer = {
-        println(s"hi from bar, y=$y")
-        23
-    }
+    override def call: Integer = {
+        println(s"hi from bar, y=$y")
+        23
+    }
 
-    @Command(name = "baz", description = Array("I'm a subcommand of `bar`"))
-    def baz(@Option(names = Array("-z")) z: Int): Int = {
-        println(s"hi from baz, z=$z")
-        45
-    }
-}
+ @Command(name = "baz", description = Array("I'm a subcommand of `bar`")) + def baz(@Option(names = Array("-z")) z: Int): Int = { + println(s"hi from baz, z=$z") + 45 + } +}
@@ -11670,7 +11395,7 @@

-
alias foo='java Foo'
+
alias foo='java Foo'
@@ -11678,11 +11403,11 @@

-
$ foo -x 123
-hi from foo, x=123
+
$ foo -x 123
+hi from foo, x=123
 
-#check the exit code
-$ echo $?
+#check the exit code
+$ echo $?
 0
@@ -11691,11 +11416,11 @@

-
$ foo -x 123 bar -y=456
-hi from bar, y=456
+
$ foo -x 123 bar -y=456
+hi from bar, y=456
 
-#check the exit code
-$ echo $?
+#check the exit code
+$ echo $?
 23
@@ -11704,11 +11429,11 @@

-
$ foo bar baz -z=789
-hi from baz, z=789
+
$ foo bar baz -z=789
+hi from baz, z=789
 
-#check the exit code
-$ echo $?
+#check the exit code
+$ echo $?
 45
@@ -11729,121 +11454,121 @@

Java
-
@Command(subcommands = {Sub1.class, Sub2.class, Sub3.class})
-class MyApp implements Runnable {
+
@Command(subcommands = {Sub1.class, Sub2.class, Sub3.class})
+class MyApp implements Runnable {
 
-    // A reference to this method can be used as a custom execution strategy
-    // that first calls the init() method,
-    // and then delegates to the default execution strategy.
-    private int executionStrategy(ParseResult parseResult) {
-        init(); // custom initialization to be done before executing any command or subcommand
-        return new CommandLine.RunLast().execute(parseResult); // default execution strategy
-    }
+    // A reference to this method can be used as a custom execution strategy
+    // that first calls the init() method,
+    // and then delegates to the default execution strategy.
+    private int executionStrategy(ParseResult parseResult) {
+        init(); // custom initialization to be done before executing any command or subcommand
+        return new CommandLine.RunLast().execute(parseResult); // default execution strategy
+    }
 
-    private void init() {
-        // ...
-    }
+    private void init() {
+        // ...
+    }
 
-    public static void main(String[] args) {
-        MyApp app = new MyApp();
-        new CommandLine(app)
-                .setExecutionStrategy(app::executionStrategy)
-                .execute(args);
-    }
+    public static void main(String[] args) {
+        MyApp app = new MyApp();
+        new CommandLine(app)
+                .setExecutionStrategy(app::executionStrategy)
+                .execute(args);
+    }
 
-    // ...
-}
+ // ... +}

Groovy
-
@Command(subcommands = [Sub1.class, Sub2.class, Sub3.class])
-class MyApp implements Runnable {
+
@Command(subcommands = [Sub1.class, Sub2.class, Sub3.class])
+class MyApp implements Runnable {
 
-    // A reference to this method can be used as a custom execution strategy
-    // that first calls the init() method,
-    // and then delegates to the default execution strategy.
-    def int executionStrategy(ParseResult parseResult) {
-        init(); // custom initialization to be done before executing any command or subcommand
-        return new CommandLine.RunLast().execute(parseResult); // default execution strategy
-    }
+    // A reference to this method can be used as a custom execution strategy
+    // that first calls the init() method,
+    // and then delegates to the default execution strategy.
+    def int executionStrategy(ParseResult parseResult) {
+        init(); // custom initialization to be done before executing any command or subcommand
+        return new CommandLine.RunLast().execute(parseResult); // default execution strategy
+    }
 
-    def void init() {
-        // ...
-    }
+    def void init() {
+        // ...
+    }
 
-    public static void main(String[] args) {
-        def app = new MyApp();
-        new CommandLine(app)
-                .setExecutionStrategy(app.&executionStrategy)
-                .execute(args);
-    }
+    public static void main(String[] args) {
+        def app = new MyApp();
+        new CommandLine(app)
+                .setExecutionStrategy(app.&executionStrategy)
+                .execute(args);
+    }
 
-    // ...
-}
+ // ... +}
Kotlin
-
@Command(subcommands = [Sub1::class, Sub2::class, Sub3::class])
-class MyApp : Runnable {
+
@Command(subcommands = [Sub1::class, Sub2::class, Sub3::class])
+class MyApp : Runnable {
 
-    // A reference to this method can be used as a custom execution strategy
-    // that first calls the init() method,
-    // and then delegates to the default execution strategy.
-    private fun executionStrategy(parseResult: ParseResult): Int {
-        init() // custom initialization to be done before executing any command or subcommand
-        return RunLast().execute(parseResult) // default execution strategy
-    }
+    // A reference to this method can be used as a custom execution strategy
+    // that first calls the init() method,
+    // and then delegates to the default execution strategy.
+    private fun executionStrategy(parseResult: ParseResult): Int {
+        init() // custom initialization to be done before executing any command or subcommand
+        return RunLast().execute(parseResult) // default execution strategy
+    }
 
-    private fun init() {
-        // ...
-    }
+    private fun init() {
+        // ...
+    }
 
-    companion object {
-        @JvmStatic
-        fun main(args: Array<String>) {
-            val app = MyApp()
-            CommandLine(app)
-                .setExecutionStrategy {
-                     parseResult: ParseResult -> app.executionStrategy(parseResult) }
-                .execute(*args)
-        }
-    }
+    companion object {
+        @JvmStatic
+        fun main(args: Array<String>) {
+            val app = MyApp()
+            CommandLine(app)
+                .setExecutionStrategy {
+                     parseResult: ParseResult -> app.executionStrategy(parseResult) }
+                .execute(*args)
+        }
+    }
 
-    // ...
-}
+ // ... +}
Scala
-
@Command(subcommands = Array(classOf[Sub1], classOf[Sub2], classOf[Sub3]))
-class MyApp extends Runnable {
+
@Command(subcommands = Array(classOf[Sub1], classOf[Sub2], classOf[Sub3]))
+class MyApp extends Runnable {
 
-    // A reference to this method can be used as a custom execution strategy
-    // that first calls the init() method,
-    // and then delegates to the default execution strategy.
-    private def executionStrategy(parseResult: ParseResult ) = {
-        init() // custom initialization to be done before executing any command or subcommand
-        new CommandLine.RunLast().execute(parseResult) // default execution strategy
-    }
+    // A reference to this method can be used as a custom execution strategy
+    // that first calls the init() method,
+    // and then delegates to the default execution strategy.
+    private def executionStrategy(parseResult: ParseResult ) = {
+        init() // custom initialization to be done before executing any command or subcommand
+        new CommandLine.RunLast().execute(parseResult) // default execution strategy
+    }
 
-    private def init(): Unit = {
-        // ...
-    }
-}
+    private def init(): Unit = {
+        // ...
+    }
+}
 
-object MyApp {
-    def main(args: Array[String]): Unit = {
-        val app = new MyApp
-        new CommandLine(app)
-            .setExecutionStrategy(app.executionStrategy)
-            .execute(args: _*)
-    }
-}
+object MyApp { + def main(args: Array[String]): Unit = { + val app = new MyApp + new CommandLine(app) + .setExecutionStrategy(app.executionStrategy) + .execute(args: _*) + } +}
Groovy
-
@Command(name = "fileutils", subcommands = [ListFiles.class])
-class FileUtils {
+
@Command(name = "fileutils", subcommands = [ListFiles.class])
+class FileUtils {
 
-    @Option(names = ["-d", "--directory"],
-            description = "this option applies to all subcommands")
-    def baseDirectory;
-}
+ @Option(names = ["-d", "--directory"], + description = "this option applies to all subcommands") + def baseDirectory; +}
Kotlin
-
@Command(name = "fileutils", subcommands = [ListFiles::class])
-class FileUtils {
+
@Command(name = "fileutils", subcommands = [ListFiles::class])
+class FileUtils {
 
-    @Option(names = ["-d", "--directory"],
-            description = ["this option applies to all subcommands"])
-    var baseDirectory: File? = null
-}
+ @Option(names = ["-d", "--directory"], + description = ["this option applies to all subcommands"]) + var baseDirectory: File? = null +}
Scala
-
@Command(name = "fileutils", subcommands = Array(classOf[ListFiles]))
-class FileUtils {
+
@Command(name = "fileutils", subcommands = Array(classOf[ListFiles]))
+class FileUtils {
 
-    @Option(names = Array("-d", "--directory"),
-            description = Array("this option applies to all subcommands"))
-    var baseDirectory: File = null
-}
+ @Option(names = Array("-d", "--directory"), + description = Array("this option applies to all subcommands")) + var baseDirectory: File = null +}
Kotlin
-
@Command(name = "list")
-class ListFiles : Runnable {
+
@Command(name = "list")
+class ListFiles : Runnable {
 
-    @ParentCommand
-    private val parent: FileUtils? = null // picocli injects reference to parent command
+    @ParentCommand
+    private val parent: FileUtils? = null // picocli injects reference to parent command
 
-    @Option(names = ["-r", "--recursive"],
-            description = ["Recursively list subdirectories"])
-    private var recursive = false
+    @Option(names = ["-r", "--recursive"],
+            description = ["Recursively list subdirectories"])
+    private var recursive = false
 
-    override fun run() {
-        list(File(parent!!.baseDirectory, "."))
-    }
+    override fun run() {
+        list(File(parent!!.baseDirectory, "."))
+    }
 
-    private fun list(dir: File) {
-        println(dir.absolutePath)
-        if (dir.isDirectory) {
-            for (f in dir.listFiles()) {
-                if (f.isDirectory && recursive) {
-                    list(f)
-                } else {
-                    println(f.absolutePath)
-                }
-            }
-        }
-    }
-}
+ private fun list(dir: File) { + println(dir.absolutePath) + if (dir.isDirectory) { + for (f in dir.listFiles()) { + if (f.isDirectory && recursive) { + list(f) + } else { + println(f.absolutePath) + } + } + } + } +}

@@ -11990,15 +11715,15 @@

1
Java
-
@Command(name = "status", aliases = {"st"}, description = "Show the working tree status.")
-class GitStatus { ... }
+
@Command(name = "status", aliases = {"st"}, description = "Show the working tree status.")
+class GitStatus { ... }
Kotlin
-
@Command(name = "status", aliases = ["st"], description = ["Show the working tree status."])
-class GitStatus { ... }
+
@Command(name = "status", aliases = ["st"], description = ["Show the working tree status."])
+class GitStatus { ... }
Kotlin
-
@Command(name = "app", scope = ScopeType.INHERIT,
-         mixinStandardHelpOptions = true, version = ["app version 1.0"],
-         header = ["App header"],
-         description = ["App description"],
-         footerHeading = "Copyright%n", footer = ["(c) Copyright by the authors"],
-         showAtFileInUsageHelp = true)
-class App : Runnable {
-    @Option(names = ["-x"]) var x = 0
+
@Command(name = "app", scope = ScopeType.INHERIT,
+         mixinStandardHelpOptions = true, version = ["app version 1.0"],
+         header = ["App header"],
+         description = ["App description"],
+         footerHeading = "Copyright%n", footer = ["(c) Copyright by the authors"],
+         showAtFileInUsageHelp = true)
+class App : Runnable {
+    @Option(names = ["-x"]) var x = 0
 
-    override fun run() { println("Hello from app!\nx = $x") }
+    override fun run() { println("Hello from app!\nx = $x") }
 
-    @Command(header = ["Subcommand header"], description = ["Subcommand description"])
-    fun sub(@Option(names = ["-y"]) y: Int) {
-        println("Hello from sub!\ny = $y")
-    }
-}
+ @Command(header = ["Subcommand header"], description = ["Subcommand description"]) + fun sub(@Option(names = ["-y"]) y: Int) { + println("Hello from sub!\ny = $y") + } +}
@@ -12173,73 +11898,73 @@

17.
Java
-
@Command(name = "app", subcommands = Sub.class)
-class App implements Runnable {
-    private static Logger logger = LogManager.getLogger(App.class);
+
@Command(name = "app", subcommands = Sub.class)
+class App implements Runnable {
+    private static Logger logger = LogManager.getLogger(App.class);
 
-    @Option(names = "-x", scope = ScopeType.LOCAL) // option is not shared: this is the default
-    int x;
+    @Option(names = "-x", scope = ScopeType.LOCAL) // option is not shared: this is the default
+    int x;
 
-    @Option(names = "-v", scope = ScopeType.INHERIT) // option is shared with subcommands
-    public void setVerbose(boolean[] verbose) {
-        // Configure log4j.
-        // (This is a simplistic example: a real application may use more levels and
-        // perhaps configure only the ConsoleAppender level instead of the root log level.)
-        Configurator.setRootLevel(verbose.length > 0 ? Level.DEBUG : Level.INFO);
-    }
+    @Option(names = "-v", scope = ScopeType.INHERIT) // option is shared with subcommands
+    public void setVerbose(boolean[] verbose) {
+        // Configure log4j.
+        // (This is a simplistic example: a real application may use more levels and
+        // perhaps configure only the ConsoleAppender level instead of the root log level.)
+        Configurator.setRootLevel(verbose.length > 0 ? Level.DEBUG : Level.INFO);
+    }
 
-    public void run() {
-        logger.debug("-x={}", x);
-    }
-}
+    public void run() {
+        logger.debug("-x={}", x);
+    }
+}
 
-@Command(name = "sub")
-class Sub implements Runnable {
-    private static Logger logger = LogManager.getLogger(Sub.class);
+@Command(name = "sub")
+class Sub implements Runnable {
+    private static Logger logger = LogManager.getLogger(Sub.class);
 
-    @Option(names = "-y")
-    int y;
+    @Option(names = "-y")
+    int y;
 
-    public void run() {
-        logger.debug("-y={}", y);
-    }
-}
+ public void run() { + logger.debug("-y={}", y); + } +}
Kotlin
-
@Command(name = "app", subcommands = [Sub::class])
-class App : Runnable {
-    private val logger = LogManager.getLogger(App::class.java)
+
@Command(name = "app", subcommands = [Sub::class])
+class App : Runnable {
+    private val logger = LogManager.getLogger(App::class.java)
 
-    @Option(names = ["-x"], scope = ScopeType.LOCAL) // option is not shared by default
-    var x = 0
+    @Option(names = ["-x"], scope = ScopeType.LOCAL) // option is not shared by default
+    var x = 0
 
-    @Option(names = ["-v"], scope = ScopeType.INHERIT) // option is shared with subcommands
-    fun setVerbose(verbose: BooleanArray) {
-        // Configure log4j.
-        // (This is a simplistic example: a real application may use more levels and
-        // perhaps configure only the ConsoleAppender level instead of the root log level.)
-        Configurator.setRootLevel(if (verbose.size > 0) Level.DEBUG else Level.INFO)
-    }
+    @Option(names = ["-v"], scope = ScopeType.INHERIT) // option is shared with subcommands
+    fun setVerbose(verbose: BooleanArray) {
+        // Configure log4j.
+        // (This is a simplistic example: a real application may use more levels and
+        // perhaps configure only the ConsoleAppender level instead of the root log level.)
+        Configurator.setRootLevel(if (verbose.size > 0) Level.DEBUG else Level.INFO)
+    }
 
-    override fun run() {
-        logger.debug("-x={}", x)
-    }
-}
+    override fun run() {
+        logger.debug("-x={}", x)
+    }
+}
 
-@Command(name = "sub")
-class Sub : Runnable {
-    private val logger = LogManager.getLogger(Sub::class.java)
+@Command(name = "sub")
+class Sub : Runnable {
+    private val logger = LogManager.getLogger(Sub::class.java)
 
-    @Option(names = ["-y"])
-    var y = 0
+    @Option(names = ["-y"])
+    var y = 0
 
-    override fun run() {
-        logger.debug("-y={}", y)
-    }
-}
+ override fun run() { + logger.debug("-y={}", y) + } +}
Kotlin
-
fun main(args: Array<String>) {
-    // Set up the parser
-    val commandLine = CommandLine(Git())
+
fun main(args: Array<String>) {
+    // Set up the parser
+    val commandLine = CommandLine(Git())
 
-    // add subcommands programmatically (not necessary if the parent command
-    // declaratively registers the subcommands via annotation)
-    commandLine.addSubcommand("status",   GitStatus())
-               .addSubcommand("commit",   GitCommit())
-               // ...
+    // add subcommands programmatically (not necessary if the parent command
+    // declaratively registers the subcommands via annotation)
+    commandLine.addSubcommand("status",   GitStatus())
+               .addSubcommand("commit",   GitCommit())
+               // ...
 
-    // Invoke the parseArgs method to parse the arguments
-    val parsed = commandLine.parseArgs(*args)
-    handleParseResult(parsed)
-}
+ // Invoke the parseArgs method to parse the arguments + val parsed = commandLine.parseArgs(*args) + handleParseResult(parsed) +}
@@ -12351,43 +12076,43 @@

Java
-
private void handleParseResult(ParseResult parsed) {
-    assert parsed.subcommand() != null : "at least 1 command and 1 subcommand found";
+
private void handleParseResult(ParseResult parsed) {
+    assert parsed.subcommand() != null : "at least 1 command and 1 subcommand found";
 
-    ParseResult sub = parsed.subcommand();
-    assert parsed.commandSpec().userObject().getClass() == Git.class       : "main command";
-    assert    sub.commandSpec().userObject().getClass() == GitStatus.class : "subcommand";
+    ParseResult sub = parsed.subcommand();
+    assert parsed.commandSpec().userObject().getClass() == Git.class       : "main command";
+    assert    sub.commandSpec().userObject().getClass() == GitStatus.class : "subcommand";
 
-    Git git = (Git) parsed.commandSpec().userObject();
-    assert git.gitDir.equals(new File("/home/rpopma/picocli"));
+    Git git = (Git) parsed.commandSpec().userObject();
+    assert git.gitDir.equals(new File("/home/rpopma/picocli"));
 
-    GitStatus gitstatus = (GitStatus) sub.commandSpec().userObject();
-    assert  gitstatus.shortFormat              : "git status -s";
-    assert  gitstatus.branchInfo               : "git status -b";
-    assert !gitstatus.showIgnored              : "git status --showIgnored not specified";
-    assert  gitstatus.mode == GitStatusMode.no : "git status -u=no";
-}
+ GitStatus gitstatus = (GitStatus) sub.commandSpec().userObject(); + assert gitstatus.shortFormat : "git status -s"; + assert gitstatus.branchInfo : "git status -b"; + assert !gitstatus.showIgnored : "git status --showIgnored not specified"; + assert gitstatus.mode == GitStatusMode.no : "git status -u=no"; +}

Kotlin
-
private fun handleParseResult(parsed: CommandLine.ParseResult) {
-    assert(parsed.subcommand() != null) { "at least 1 command and 1 subcommand found" }
+
private fun handleParseResult(parsed: CommandLine.ParseResult) {
+    assert(parsed.subcommand() != null) { "at least 1 command and 1 subcommand found" }
 
-    val sub = parsed.subcommand()
-    assert(parsed.commandSpec().userObject().javaClass == Git::class.java) { "main command" }
-    assert(sub.commandSpec().userObject().javaClass == GitStatus::class.java) { "subcommand" }
+    val sub = parsed.subcommand()
+    assert(parsed.commandSpec().userObject().javaClass == Git::class.java) { "main command" }
+    assert(sub.commandSpec().userObject().javaClass == GitStatus::class.java) { "subcommand" }
 
-    val git = parsed.commandSpec().userObject() as Git
-    assert(git.gitDir == File("/home/rpopma/picocli"))
+    val git = parsed.commandSpec().userObject() as Git
+    assert(git.gitDir == File("/home/rpopma/picocli"))
 
-    val gitstatus = sub.commandSpec().userObject() as GitStatus
-    assert(gitstatus.shortFormat)               { "git status -s" }
-    assert(gitstatus.branchInfo)                { "git status -b" }
-    assert(!gitstatus.showIgnored)              { "git status --showIgnored not specified" }
-    assert(gitstatus.mode === GitStatusMode.no) { "git status -u=no" }
-}
+ val gitstatus = sub.commandSpec().userObject() as GitStatus + assert(gitstatus.shortFormat) { "git status -s" } + assert(gitstatus.branchInfo) { "git status -b" } + assert(!gitstatus.showIgnored) { "git status --showIgnored not specified" } + assert(gitstatus.mode === GitStatusMode.no) { "git status -u=no" } +}
Kotlin
-
@Command(name = "main", subcommands = [
-    ChildCommand1::class,
-    ChildCommand2::class,
-    ChildCommand3::class]
-)
-class MainCommand { }
+
@Command(name = "main", subcommands = [
+    ChildCommand1::class,
+    ChildCommand2::class,
+    ChildCommand3::class]
+)
+class MainCommand { }
 
-@Command(name = "cmd3", subcommands = [
-    GrandChild3Command1::class,
-    GrandChild3Command2::class,
-    GrandChild3Command3::class]
-)
-class ChildCommand3 { }
+@Command(name = "cmd3", subcommands = [
+    GrandChild3Command1::class,
+    GrandChild3Command2::class,
+    GrandChild3Command3::class]
+)
+class ChildCommand3 { }
 
-@Command(name = "cmd3sub3", subcommands = [
-    GreatGrandChild3Command3_1::class,
-    GreatGrandChild3Command3_2::class]
-)
-class GrandChild3Command3 {}
-// ...
+@Command(name = "cmd3sub3", subcommands = [ + GreatGrandChild3Command3_1::class, + GreatGrandChild3Command3_2::class] +) +class GrandChild3Command3 {} +// ...
Kotlin
-
val commandLine = CommandLine(MainCommand())
-    .addSubcommand("cmd1",             ChildCommand1())
-    .addSubcommand("cmd2",             ChildCommand2())
-    .addSubcommand("cmd3", CommandLine(ChildCommand3())
-        .addSubcommand("cmd3sub1",             GrandChild3Command1())
-        .addSubcommand("cmd3sub2",             GrandChild3Command2())
-        .addSubcommand("cmd3sub3", CommandLine(GrandChild3Command3())
-            .addSubcommand("cmd3sub3sub1", GreatGrandChild3Command3_1())
-            .addSubcommand("cmd3sub3sub2", GreatGrandChild3Command3_2())
-        )
-    )
+
val commandLine = CommandLine(MainCommand())
+    .addSubcommand("cmd1",             ChildCommand1())
+    .addSubcommand("cmd2",             ChildCommand2())
+    .addSubcommand("cmd3", CommandLine(ChildCommand3())
+        .addSubcommand("cmd3sub1",             GrandChild3Command1())
+        .addSubcommand("cmd3sub2",             GrandChild3Command2())
+        .addSubcommand("cmd3sub3", CommandLine(GrandChild3Command3())
+            .addSubcommand("cmd3sub3sub1", GreatGrandChild3Command3_1())
+            .addSubcommand("cmd3sub3sub2", GreatGrandChild3Command3_2())
+        )
+    )
@@ -12516,46 +12241,46 @@

17.13.1. Example
Java
-
@Command(name = "myapp", subcommandsRepeatable = true)
-class MyApp implements Runnable {
+
@Command(name = "myapp", subcommandsRepeatable = true)
+class MyApp implements Runnable {
 
-    @Command
-    void add(@Option(names = "-x") String x, @Option(names = "-w") double w) { ... }
+    @Command
+    void add(@Option(names = "-x") String x, @Option(names = "-w") double w) { ... }
 
-    @Command
-    void list(@Option(names = "--where") String where) { ... }
+    @Command
+    void list(@Option(names = "--where") String where) { ... }
 
-    @Command(name = "send-report")
-    void sendReport(@Option(names = "--to", split = ",") String[] recipients) { ... }
+    @Command(name = "send-report")
+    void sendReport(@Option(names = "--to", split = ",") String[] recipients) { ... }
 
-    public static void main(String... args) {
-        new CommandLine(new MyApp()).execute(args);
-    }
-}
+ public static void main(String... args) { + new CommandLine(new MyApp()).execute(args); + } +}

Kotlin
-
@Command(name = "myapp", subcommandsRepeatable = true)
-class MyApp : Runnable {
+
@Command(name = "myapp", subcommandsRepeatable = true)
+class MyApp : Runnable {
 
-    @Command
-    fun add(@Option(names = ["-x"]) x: String, @Option(names = ["-w"]) w: Double) { ... }
+    @Command
+    fun add(@Option(names = ["-x"]) x: String, @Option(names = ["-w"]) w: Double) { ... }
 
-    @Command
-    fun list(@Option(names = ["--where"]) where: String) { ... }
+    @Command
+    fun list(@Option(names = ["--where"]) where: String) { ... }
 
-    @Command(name = "send-report")
-    fun sendReport(@Option(names = ["--to"], split = ",") recipients: Array<String>) { ... }
+    @Command(name = "send-report")
+    fun sendReport(@Option(names = ["--to"], split = ",") recipients: Array<String>) { ... }
 
-    companion object {
-        @JvmStatic
-        fun main(args: Array<String>) {
-            CommandLine(MyApp()).execute(*args)
-        }
-    }
-}
+ companion object { + @JvmStatic + fun main(args: Array<String>) { + CommandLine(MyApp()).execute(*args) + } + } +}
@@ -12563,11 +12288,11 @@

17.13.1. Example
-
myapp add -x=item1 -w=0.2 \
-      add -x=item2 -w=0.5 \
-      add -x=item3 -w=0.7 \
-      list --where "w>0.2" \
-      send-report --to=recipient@myorg.com
+
myapp add -x=item1 -w=0.2 \
+      add -x=item2 -w=0.5 \
+      add -x=item3 -w=0.7 \
+      list --where "w>0.2" \
+      send-report --to=recipient@myorg.com

@@ -12638,27 +12363,27 @@

Java
-
CommandLine commandLine = new CommandLine(new Git());
+
CommandLine commandLine = new CommandLine(new Git());
 
-// add subcommands programmatically (not necessary if the parent command
-// declaratively registers the subcommands via annotation)
-commandLine.addSubcommand("status",   new GitStatus());
-commandLine.addSubcommand("commit",   new GitCommit());
-...
-commandLine.usage(System.out);
+// add subcommands programmatically (not necessary if the parent command +// declaratively registers the subcommands via annotation) +commandLine.addSubcommand("status", new GitStatus()); +commandLine.addSubcommand("commit", new GitCommit()); +... +commandLine.usage(System.out);

Kotlin
-
val commandLine = CommandLine(Git())
+
val commandLine = CommandLine(Git())
 
-// add subcommands programmatically (not necessary if the parent command
-// declaratively registers the subcommands via annotation)
-commandLine.addSubcommand("status",   GitStatus())
-commandLine.addSubcommand("commit",   GitCommit())
+// add subcommands programmatically (not necessary if the parent command
+// declaratively registers the subcommands via annotation)
+commandLine.addSubcommand("status",   GitStatus())
+commandLine.addSubcommand("commit",   GitCommit())
 
-commandLine.usage(System.out)
+commandLine.usage(System.out)
Kotlin
-
@Command(name = "git", mixinStandardHelpOptions = true,
-        version = ["subcommand demo - picocli 4.0"],
-        subcommands = [HelpCommand::class],
-        description = ["Git is a fast, scalable, distributed revision control " +
-                       "system with an unusually rich command set that provides both " +
-                       "high-level operations and full access to internals."],
-        commandListHeading = "%nCommands:%n%nThe most commonly used git commands are:%n")
-class Git : Runnable {
-
-    @Option(names = ["--git-dir"], description = ["Set the path to the repository."])
-    lateinit var gitDir: File
-}
+
@Command(name = "git", mixinStandardHelpOptions = true,
+        version = ["subcommand demo - picocli 4.0"],
+        subcommands = [HelpCommand::class],
+        description = ["Git is a fast, scalable, distributed revision control " +
+                       "system with an unusually rich command set that provides both " +
+                       "high-level operations and full access to internals."],
+        commandListHeading = "%nCommands:%n%nThe most commonly used git commands are:%n")
+class Git : Runnable {
+
+    @Option(names = ["--git-dir"], description = ["Set the path to the repository."])
+    lateinit var gitDir: File
+}
Kotlin
-
@Command(name = "commit", description = ["..."] )
-class Commit : Runnable {
-    @Spec
-    lateinit var spec: CommandSpec
+
@Command(name = "commit", description = ["..."] )
+class Commit : Runnable {
+    @Spec
+    lateinit var spec: CommandSpec
 
-    override fun run() {
-        if (shouldShowHelp()) {
-            spec.commandLine().usage(System.out);
-        }
-    }
-}
+ override fun run() { + if (shouldShowHelp()) { + spec.commandLine().usage(System.out); + } + } +}
@@ -12802,27 +12527,27 @@

1
Java
-
@Command(name = "foo", description = "This is a visible subcommand")
-class Foo { }
+
@Command(name = "foo", description = "This is a visible subcommand")
+class Foo { }
 
-@Command(name = "bar", description = "This is a hidden subcommand", hidden = true)
-class Bar { }
+@Command(name = "bar", description = "This is a hidden subcommand", hidden = true)
+class Bar { }
 
-@Command(name = "app", subcommands = {Foo.class, Bar.class})
-class App { }
+@Command(name = "app", subcommands = {Foo.class, Bar.class}) +class App { }
Kotlin
-
@Command(name = "foo", description = ["This is a visible subcommand"])
-class Foo { }
+
@Command(name = "foo", description = ["This is a visible subcommand"])
+class Foo { }
 
-@Command(name = "bar", description = ["This is a hidden subcommand"], hidden = true)
-class Bar { }
+@Command(name = "bar", description = ["This is a hidden subcommand"], hidden = true)
+class Bar { }
 
-@Command(name = "app", mixinStandardHelpOptions = true, subcommands = [Foo::class, Bar::class])
-class App { }
+@Command(name = "app", mixinStandardHelpOptions = true, subcommands = [Foo::class, Bar::class]) +class App { }
@@ -12848,7 +12573,7 @@

17.16

-
@Command(helpCommand = true)
+
@Command(helpCommand = true)

@@ -12869,39 +12594,39 @@

<
Java
-
@Command(name = "git", synopsisSubcommandLabel = "COMMAND", subcommands = { ... })
-class Git implements Runnable {
-    @Spec CommandSpec spec;
+
@Command(name = "git", synopsisSubcommandLabel = "COMMAND", subcommands = { ... })
+class Git implements Runnable {
+    @Spec CommandSpec spec;
 
-    public void run() {
-        throw new ParameterException(spec.commandLine(), "Missing required subcommand");
-    }
+    public void run() {
+        throw new ParameterException(spec.commandLine(), "Missing required subcommand");
+    }
 
-    public static void main(String... args) {
-        System.exit(new CommandLine(new Git()).execute(args));
-    }
-}
+ public static void main(String... args) { + System.exit(new CommandLine(new Git()).execute(args)); + } +}
Kotlin
-
@Command(name = "git", synopsisSubcommandLabel = "COMMAND", subcommands = [ ... ])
-class Git : Runnable {
-    @Spec
-    lateinit var spec: CommandSpec
+
@Command(name = "git", synopsisSubcommandLabel = "COMMAND", subcommands = [ ... ])
+class Git : Runnable {
+    @Spec
+    lateinit var spec: CommandSpec
 
-    override fun run() {
-        throw ParameterException(spec.commandLine(), "Missing required subcommand")
-    }
+    override fun run() {
+        throw ParameterException(spec.commandLine(), "Missing required subcommand")
+    }
 
-    companion object {
-        @JvmStatic
-        fun main(args: Array<String>) {
-            exitProcess(CommandLine(Git()).execute(*args))
-        }
-    }
-}
+ companion object { + @JvmStatic + fun main(args: Array<String>) { + exitProcess(CommandLine(Git()).execute(*args)) + } + } +}
@@ -12957,35 +12682,35 @@

18.1. Subclassi
Java
-
@Command(synopsisHeading      = "%nUsage:%n%n",
-         descriptionHeading   = "%nDescription:%n%n",
-         parameterListHeading = "%nParameters:%n%n",
-         optionListHeading    = "%nOptions:%n%n",
-         commandListHeading   = "%nCommands:%n%n")
-public class ReusableOptions {
-
-    @Option(names = { "-v", "--verbose" }, description = {
-            "Specify multiple -v options to increase verbosity.",
-            "For example, `-v -v -v` or `-vvv`" })
-    protected boolean[] verbosity = new boolean[0];
-}
+
@Command(synopsisHeading      = "%nUsage:%n%n",
+         descriptionHeading   = "%nDescription:%n%n",
+         parameterListHeading = "%nParameters:%n%n",
+         optionListHeading    = "%nOptions:%n%n",
+         commandListHeading   = "%nCommands:%n%n")
+public class ReusableOptions {
+
+    @Option(names = { "-v", "--verbose" }, description = {
+            "Specify multiple -v options to increase verbosity.",
+            "For example, `-v -v -v` or `-vvv`" })
+    protected boolean[] verbosity = new boolean[0];
+}
Kotlin
-
@Command(synopsisHeading      = "%nUsage:%n%n",
-         descriptionHeading   = "%nDescription:%n%n",
-         parameterListHeading = "%nParameters:%n%n",
-         optionListHeading    = "%nOptions:%n%n",
-         commandListHeading   = "%nCommands:%n%n")
-public open class ReusableOptions {
-
-    @Option(names = ["-v", "--verbose"], description = [
-            "Specify multiple -v options to increase verbosity.",
-            "For example, `-v -v -v` or `-vvv`"])
-    protected var verbosity = BooleanArray(0)
-}
+
@Command(synopsisHeading      = "%nUsage:%n%n",
+         descriptionHeading   = "%nDescription:%n%n",
+         parameterListHeading = "%nParameters:%n%n",
+         optionListHeading    = "%nOptions:%n%n",
+         commandListHeading   = "%nCommands:%n%n")
+public open class ReusableOptions {
+
+    @Option(names = ["-v", "--verbose"], description = [
+            "Specify multiple -v options to increase verbosity.",
+            "For example, `-v -v -v` or `-vvv`"])
+    protected var verbosity = BooleanArray(0)
+}
@@ -12994,20 +12719,20 @@

18.1. Subclassi
Java
-
@Command(name = "zip", description = "Example reuse by subclassing")
-public class MyCommand extends ReusableOptions { /* ... */ }
+
@Command(name = "zip", description = "Example reuse by subclassing")
+public class MyCommand extends ReusableOptions { /* ... */ }
Kotlin
-
@Command(name = "zip", description = ["Example reuse by subclassing"])
-class MyCommand : ReusableOptions(), Runnable {
+
@Command(name = "zip", description = ["Example reuse by subclassing"])
+class MyCommand : ReusableOptions(), Runnable {
 
-    override fun run() {
-        // ...
-    }
-}
+ override fun run() { + // ... + } +}

@@ -13033,35 +12758,35 @@

18.2. Mixins

Java
-
@Command(synopsisHeading      = "%nUsage:%n%n",
-         descriptionHeading   = "%nDescription:%n%n",
-         parameterListHeading = "%nParameters:%n%n",
-         optionListHeading    = "%nOptions:%n%n",
-         commandListHeading   = "%nCommands:%n%n")
-public class ReusableOptions {
-
-    @Option(names = { "-v", "--verbose" }, description = {
-            "Specify multiple -v options to increase verbosity.",
-            "For example, `-v -v -v` or `-vvv`" })
-    protected boolean[] verbosity = new boolean[0];
-}
+
@Command(synopsisHeading      = "%nUsage:%n%n",
+         descriptionHeading   = "%nDescription:%n%n",
+         parameterListHeading = "%nParameters:%n%n",
+         optionListHeading    = "%nOptions:%n%n",
+         commandListHeading   = "%nCommands:%n%n")
+public class ReusableOptions {
+
+    @Option(names = { "-v", "--verbose" }, description = {
+            "Specify multiple -v options to increase verbosity.",
+            "For example, `-v -v -v` or `-vvv`" })
+    protected boolean[] verbosity = new boolean[0];
+}
Kotlin
-
@Command(synopsisHeading      = "%nUsage:%n%n",
-         descriptionHeading   = "%nDescription:%n%n",
-         parameterListHeading = "%nParameters:%n%n",
-         optionListHeading    = "%nOptions:%n%n",
-         commandListHeading   = "%nCommands:%n%n")
-open class ReusableOptions {
-
-    @Option(names = ["-v", "--verbose"], description = [
-            "Specify multiple -v options to increase verbosity.",
-            "For example, `-v -v -v` or `-vvv`"])
-    protected var verbosity = BooleanArray(0)
-}
+
@Command(synopsisHeading      = "%nUsage:%n%n",
+         descriptionHeading   = "%nDescription:%n%n",
+         parameterListHeading = "%nParameters:%n%n",
+         optionListHeading    = "%nOptions:%n%n",
+         commandListHeading   = "%nCommands:%n%n")
+open class ReusableOptions {
+
+    @Option(names = ["-v", "--verbose"], description = [
+            "Specify multiple -v options to increase verbosity.",
+            "For example, `-v -v -v` or `-vvv`"])
+    protected var verbosity = BooleanArray(0)
+}
@@ -13075,35 +12800,35 @@

18.2.1.
Java
-
@Command(name = "zip", description = "Example reuse with @Mixin annotation.")
-public class MyCommand {
+
@Command(name = "zip", description = "Example reuse with @Mixin annotation.")
+public class MyCommand {
 
-    // adds the options defined in ReusableOptions to this command
-    @Mixin
-    private ReusableOptions myMixin;
+    // adds the options defined in ReusableOptions to this command
+    @Mixin
+    private ReusableOptions myMixin;
 
-    @Command
-    void subcmd(@Mixin ReusableOptions opts) {
-        // ...
-    }
-}
+ @Command + void subcmd(@Mixin ReusableOptions opts) { + // ... + } +}
Kotlin
-
@Command(name = "zip", description = ["Example reuse with @Mixin annotation."])
-public class MyCommand {
+
@Command(name = "zip", description = ["Example reuse with @Mixin annotation."])
+public class MyCommand {
 
-    // adds the options defined in ReusableOptions to this command
-    @Mixin
-    lateinit var myMixin: ReusableOptions
+    // adds the options defined in ReusableOptions to this command
+    @Mixin
+    lateinit var myMixin: ReusableOptions
 
-    @Command
-    fun subcmd(@Mixin opts: ReusableOptions) : Unit {
-        // ...
-    }
-}
+ @Command + fun subcmd(@Mixin opts: ReusableOptions) : Unit { + // ... + } +}
@@ -13113,21 +12838,21 @@

18.2.1.
Java
-
MyCommand cmd = new MyCommand();
-new CommandLine(cmd).parseArgs("-vvv");
+
MyCommand cmd = new MyCommand();
+new CommandLine(cmd).parseArgs("-vvv");
 
-// the options defined in ReusableOptions have been added to the `MyCommand` command
-assert cmd.myMixin.verbosity.length == 3;
+// the options defined in ReusableOptions have been added to the `MyCommand` command +assert cmd.myMixin.verbosity.length == 3;
Kotlin
-
val cmd = MyCommand()
-CommandLine(cmd).parseArgs("-vvv")
+
val cmd = MyCommand()
+CommandLine(cmd).parseArgs("-vvv")
 
-// the options defined in ReusableOptions have been added to the `MyCommand` command
-assert(cmd.myMixin.verbosity.size == 3)
+// the options defined in ReusableOptions have been added to the `MyCommand` command +assert(cmd.myMixin.verbosity.size == 3)
@@ -13147,59 +12872,59 @@

<
Java
-
public class MyLogger {
+
public class MyLogger {
 
-    @Option(names = {"-v", "--verbose"},
-            description = "Increase verbosity. Specify multiple times to increase (-vvv).")
-    boolean[] verbosity = new boolean[0];
+    @Option(names = {"-v", "--verbose"},
+            description = "Increase verbosity. Specify multiple times to increase (-vvv).")
+    boolean[] verbosity = new boolean[0];
 
-    public void info(String pattern, Object... params) {
-        log(0, pattern, params);
-    }
+    public void info(String pattern, Object... params) {
+        log(0, pattern, params);
+    }
 
-    public void debug(String pattern, Object... params) {
-        log(1, pattern, params);
-    }
+    public void debug(String pattern, Object... params) {
+        log(1, pattern, params);
+    }
 
-    public void trace(String pattern, Object... params) {
-        log(2, pattern, params);
-    }
+    public void trace(String pattern, Object... params) {
+        log(2, pattern, params);
+    }
 
-    private void log(int level, String pattern, Object... params) {
-        if (verbosity.length > level) {
-            System.err.printf(pattern, params);
-        }
-    }
-}
+ private void log(int level, String pattern, Object... params) { + if (verbosity.length > level) { + System.err.printf(pattern, params); + } + } +}
Kotlin
-
class MyLogger {
+
class MyLogger {
 
-    @Option(names = ["-v", "--verbose"],
-            description = ["Increase verbosity. Specify multiple times to increase (-vvv)."])
-    var verbosity = BooleanArray(0)
+    @Option(names = ["-v", "--verbose"],
+            description = ["Increase verbosity. Specify multiple times to increase (-vvv)."])
+    var verbosity = BooleanArray(0)
 
-    fun info(pattern: String, vararg params: Any) {
-        log(0, pattern, *params)
-    }
+    fun info(pattern: String, vararg params: Any) {
+        log(0, pattern, *params)
+    }
 
-    fun debug(pattern: String, vararg params: Any) {
-        log(1, pattern, *params)
-    }
+    fun debug(pattern: String, vararg params: Any) {
+        log(1, pattern, *params)
+    }
 
-    fun trace(pattern: String, vararg params: Any) {
-        log(2, pattern, *params)
-    }
+    fun trace(pattern: String, vararg params: Any) {
+        log(2, pattern, *params)
+    }
 
-    private fun log(level: Int, pattern: String, vararg params: Any) {
-        if (verbosity.size > level) {
-            System.err.printf(pattern, *params)
-        }
-    }
-}
+ private fun log(level: Int, pattern: String, vararg params: Any) { + if (verbosity.size > level) { + System.err.printf(pattern, *params) + } + } +}
@@ -13264,56 +12989,56 @@

Java
-
class AdvancedMixin {
-    @Spec(Spec.Target.MIXEE) CommandSpec mixee;
+
class AdvancedMixin {
+    @Spec(Spec.Target.MIXEE) CommandSpec mixee;
 
-    /**
+    /**
      * When the -x option is specified on any subcommand,
      * multiply its value with another integer supplied by this subcommand
      * and set the result on the top-level command.
      * @param x the value of the -x option
-     */
-    @Option(names = "-x")
-    void setValue(int x) {
-        // get another value from the command we are mixed into
-        int y = ((java.util.function.IntSupplier) mixee.userObject()).getAsInt();
+     */
+    @Option(names = "-x")
+    void setValue(int x) {
+        // get another value from the command we are mixed into
+        int y = ((java.util.function.IntSupplier) mixee.userObject()).getAsInt();
 
-        int product = x * y;
+        int product = x * y;
 
-        // set the result on the top-level (root) command
-        ((java.util.function.IntConsumer) mixee.root().userObject()).accept(product);
-    }
-}
+ // set the result on the top-level (root) command + ((java.util.function.IntConsumer) mixee.root().userObject()).accept(product); + } +}

Kotlin
-
import java.util.function.IntConsumer
-import java.util.function.IntSupplier
-// ...
+
import java.util.function.IntConsumer
+import java.util.function.IntSupplier
+// ...
 
-class AdvancedMixin {
-    @Spec(Spec.Target.MIXEE)
-    lateinit var mixee: CommandSpec
+class AdvancedMixin {
+    @Spec(Spec.Target.MIXEE)
+    lateinit var mixee: CommandSpec
 
-    /**
+    /**
      * When the -x option is specified on any subcommand,
      * multiply its value with another integer supplied by this subcommand
      * and set the result on the top-level command.
      * @param x the value of the -x option
-     */
-    @Option(names = ["-x"])
-    fun setValue(x: Int) {
-        // get another value from the command we are mixed into
-        val y = (mixee.userObject() as IntSupplier).asInt
+     */
+    @Option(names = ["-x"])
+    fun setValue(x: Int) {
+        // get another value from the command we are mixed into
+        val y = (mixee.userObject() as IntSupplier).asInt
 
-        val product = x * y
+        val product = x * y
 
-        // set the result on the top-level (root) command
-        (mixee.root().userObject() as IntConsumer).accept(product)
-    }
-}
+ // set the result on the top-level (root) command + (mixee.root().userObject() as IntConsumer).accept(product) + } +}

@@ -13327,87 +13052,87 @@

Java
-
// Define a mixin that delegates to the parent command.
-class MyMixin {
-    @ParentCommand Top top;
+
// Define a mixin that delegates to the parent command.
+class MyMixin {
+    @ParentCommand Top top;
 
-    @Option(names = {"-v", "--verbose"})
-    public void setVerbose(boolean verbose) { top.verbose = verbose; }
-}
+    @Option(names = {"-v", "--verbose"})
+    public void setVerbose(boolean verbose) { top.verbose = verbose; }
+}
 
-// An example Top-level command with a subcommand.
-// The `-v` option can be specified on the top-level command as well as its subcommands.
-@Command(subcommands = Sub.class)
-class Top implements Runnable {
-    @Option(names = {"-v", "--verbose"})
-    boolean verbose;
+// An example Top-level command with a subcommand.
+// The `-v` option can be specified on the top-level command as well as its subcommands.
+@Command(subcommands = Sub.class)
+class Top implements Runnable {
+    @Option(names = {"-v", "--verbose"})
+    boolean verbose;
 
-    public void verbose(String pattern, Object... params) {
-        if (verbose) {
-            System.out.printf(pattern, params);
-        }
-    }
+    public void verbose(String pattern, Object... params) {
+        if (verbose) {
+            System.out.printf(pattern, params);
+        }
+    }
 
-    public void run() { verbose("Hello from top%n"); }
+    public void run() { verbose("Hello from top%n"); }
 
-    public static void main(String[] args) {
-        new CommandLine(new Top()).execute(args);
-    }
-}
+    public static void main(String[] args) {
+        new CommandLine(new Top()).execute(args);
+    }
+}
 
-// Subcommand classes can mix in the `-v` option with a @Mixin-annotated field.
-@Command(name = "sub")
-class Sub implements Runnable{
-    @Mixin MyMixin mymixin;
+// Subcommand classes can mix in the `-v` option with a @Mixin-annotated field.
+@Command(name = "sub")
+class Sub implements Runnable{
+    @Mixin MyMixin mymixin;
 
-    @Override
-    public void run() { mymixin.top.verbose("Hello from sub%n"); }
-}
+ @Override + public void run() { mymixin.top.verbose("Hello from sub%n"); } +}

Kotlin
-
// Define a mixin that delegates to the parent command.
-class MyMixin {
-    @ParentCommand
-    lateinit var top: Top
+
// Define a mixin that delegates to the parent command.
+class MyMixin {
+    @ParentCommand
+    lateinit var top: Top
 
-    @Option(names = ["-v", "--verbose"])
-    fun setVerbose(verbose: Boolean) { top.verbose = verbose }
-}
+    @Option(names = ["-v", "--verbose"])
+    fun setVerbose(verbose: Boolean) { top.verbose = verbose }
+}
 
-// An example Top-level command with a subcommand.
-// The `-v` option can be specified on the top-level command as well as its subcommands.
-@Command(subcommands = [Sub::class])
-class Top : Runnable {
-    @Option(names = ["-v", "--verbose"])
-    var verbose = false
+// An example Top-level command with a subcommand.
+// The `-v` option can be specified on the top-level command as well as its subcommands.
+@Command(subcommands = [Sub::class])
+class Top : Runnable {
+    @Option(names = ["-v", "--verbose"])
+    var verbose = false
 
-    fun verbose(pattern: String, vararg params: Any) {
-        if (verbose) {
-            System.out.printf(pattern, *params)
-        }
-    }
+    fun verbose(pattern: String, vararg params: Any) {
+        if (verbose) {
+            System.out.printf(pattern, *params)
+        }
+    }
 
-    override fun run() { verbose("Hello from top%n") }
+    override fun run() { verbose("Hello from top%n") }
 
-    companion object {
-        @JvmStatic
-        fun main(args: Array<String>) {
-            CommandLine(Top()).execute(*args)
-        }
-    }
-}
+    companion object {
+        @JvmStatic
+        fun main(args: Array<String>) {
+            CommandLine(Top()).execute(*args)
+        }
+    }
+}
 
-// Subcommand classes can mix in the `-v` option with a @Mixin-annotated field.
-@Command(name = "sub")
-class Sub : Runnable {
-    @Mixin
-    lateinit var mymixin: MyMixin
+// Subcommand classes can mix in the `-v` option with a @Mixin-annotated field.
+@Command(name = "sub")
+class Sub : Runnable {
+    @Mixin
+    lateinit var mymixin: MyMixin
 
-    override fun run() { mymixin.top.verbose("Hello from sub%n") }
-}
+ override fun run() { mymixin.top.verbose("Hello from sub%n") } +}
Kotlin
-
val commandLine = CommandLine(MyCommand())
+
val commandLine = CommandLine(MyCommand())
 
-val mixin = ReusableOptions()
-commandLine.addMixin("myMixin", mixin)
+val mixin = ReusableOptions() +commandLine.addMixin("myMixin", mixin)
Kotlin
-
commandLine.parseArgs("-vvv")
+
commandLine.parseArgs("-vvv")
 
-// the options defined in ReusableOptions have been added to the zip command
-assert(mixin === commandLine.mixins["myMixin"])
-assert(mixin.verbosity.size == 3)
+// the options defined in ReusableOptions have been added to the zip command +assert(mixin === commandLine.mixins["myMixin"]) +assert(mixin.verbosity.size == 3)
@@ -13506,194 +13231,194 @@

Java
-
import org.apache.logging.log4j.*;
-import org.apache.logging.log4j.core.config.Configurator;
+
import org.apache.logging.log4j.*;
+import org.apache.logging.log4j.core.config.Configurator;
 
-import picocli.CommandLine;
-import picocli.CommandLine.*;
-import picocli.CommandLine.Model.CommandSpec;
-import static picocli.CommandLine.Spec.Target.MIXEE;
+import picocli.CommandLine;
+import picocli.CommandLine.*;
+import picocli.CommandLine.Model.CommandSpec;
+import static picocli.CommandLine.Spec.Target.MIXEE;
 
-class LoggingMixin {
-    private @Spec(MIXEE) CommandSpec mixee; // spec of the command where the @Mixin is used
+class LoggingMixin {
+    private @Spec(MIXEE) CommandSpec mixee; // spec of the command where the @Mixin is used
 
-    boolean[] verbosity = new boolean[0];
+    boolean[] verbosity = new boolean[0];
 
-    /**
+    /**
      * 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 value in a single, central place,
-        // so we find the top-level command,
-        // and store the verbosity level on our top-level command's LoggingMixin.
-        ((MyApp) mixee.root().userObject()).loggingMixin.verbosity = verbosity;
-    }
-}
-
-@Command(name = "app", subcommands = Sub.class)
-class MyApp implements Runnable {
-    private static Logger logger = LogManager.getLogger(MyApp.class);
-
-    @Mixin LoggingMixin loggingMixin;
-
-    @Override
-    public void run() {
-        logger.trace("Starting... (trace) from app");
-        logger.debug("Starting... (debug) from app");
-        logger.info ("Starting... (info)  from app");
-        logger.warn ("Starting... (warn)  from app");
-    }
-
-    private Level calcLogLevel() {
-        switch (loggingMixin.verbosity.length) {
-            case 0:  return Level.WARN;
-            case 1:  return Level.INFO;
-            case 2:  return Level.DEBUG;
-            default: return Level.TRACE;
-        }
-    }
-
-    // A reference to this method can be used as a custom execution strategy
-    // that first configures Log4j based on the specified verbosity level,
-    // and then delegates to the default execution strategy.
-    private int executionStrategy(ParseResult parseResult) {
-        Configurator.setRootLevel(calcLogLevel()); // configure log4j
-        return new CommandLine.RunLast().execute(parseResult); // default execution strategy
-    }
-
-    public static void main(String[] args) {
-        MyApp app = new MyApp();
-        new CommandLine(app)
-                .setExecutionStrategy(app::executionStrategy)
-                .execute(args);
-    }
-}
-
-@Command(name = "sub")
-class Sub implements Runnable {
-    private static Logger logger = LogManager.getLogger();
-
-    @Mixin LoggingMixin loggingMixin;
-
-    @Override
-    public void run() {
-        logger.trace("Hi (tracing)   from app sub");
-        logger.debug("Hi (debugging) from app sub");
-        logger.info ("Hi (info)      from app sub");
-        logger.warn ("Hi (warning)   from app sub");
-    }
-
-    @Command
-    void subsubmethod(@Mixin LoggingMixin loggingMixin) {
-        logger.trace("Hi (tracing)   from app sub subsubmethod");
-        logger.debug("Hi (debugging) from app sub subsubmethod");
-        logger.info ("Hi (info)      from app sub subsubmethod");
-        logger.warn ("Hi (warning)   from app sub subsubmethod");
-    }
-}
+ */ + @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 value in a single, central place, + // so we find the top-level command, + // and store the verbosity level on our top-level command's LoggingMixin. + ((MyApp) mixee.root().userObject()).loggingMixin.verbosity = verbosity; + } +} + +@Command(name = "app", subcommands = Sub.class) +class MyApp implements Runnable { + private static Logger logger = LogManager.getLogger(MyApp.class); + + @Mixin LoggingMixin loggingMixin; + + @Override + public void run() { + logger.trace("Starting... (trace) from app"); + logger.debug("Starting... (debug) from app"); + logger.info ("Starting... (info) from app"); + logger.warn ("Starting... (warn) from app"); + } + + private Level calcLogLevel() { + switch (loggingMixin.verbosity.length) { + case 0: return Level.WARN; + case 1: return Level.INFO; + case 2: return Level.DEBUG; + default: return Level.TRACE; + } + } + + // A reference to this method can be used as a custom execution strategy + // that first configures Log4j based on the specified verbosity level, + // and then delegates to the default execution strategy. + private int executionStrategy(ParseResult parseResult) { + Configurator.setRootLevel(calcLogLevel()); // configure log4j + return new CommandLine.RunLast().execute(parseResult); // default execution strategy + } + + public static void main(String[] args) { + MyApp app = new MyApp(); + new CommandLine(app) + .setExecutionStrategy(app::executionStrategy) + .execute(args); + } +} + +@Command(name = "sub") +class Sub implements Runnable { + private static Logger logger = LogManager.getLogger(); + + @Mixin LoggingMixin loggingMixin; + + @Override + public void run() { + logger.trace("Hi (tracing) from app sub"); + logger.debug("Hi (debugging) from app sub"); + logger.info ("Hi (info) from app sub"); + logger.warn ("Hi (warning) from app sub"); + } + + @Command + void subsubmethod(@Mixin LoggingMixin loggingMixin) { + logger.trace("Hi (tracing) from app sub subsubmethod"); + logger.debug("Hi (debugging) from app sub subsubmethod"); + logger.info ("Hi (info) from app sub subsubmethod"); + logger.warn ("Hi (warning) from app sub subsubmethod"); + } +}
Kotlin
-
import org.apache.logging.log4j.*
-import org.apache.logging.log4j.core.config.Configurator
+
import org.apache.logging.log4j.*
+import org.apache.logging.log4j.core.config.Configurator
 
-import picocli.CommandLine
-import picocli.CommandLine.*
-import picocli.CommandLine.Model.CommandSpec
+import picocli.CommandLine
+import picocli.CommandLine.*
+import picocli.CommandLine.Model.CommandSpec
 
-class LoggingMixin {
-    @Spec(Spec.Target.MIXEE)
-    private lateinit var mixee: CommandSpec// spec of the command where the @Mixin is used
-    var verbosity = BooleanArray(0)
+class LoggingMixin {
+    @Spec(Spec.Target.MIXEE)
+    private lateinit var mixee: CommandSpec// spec of the command where the @Mixin is used
+    var verbosity = BooleanArray(0)
 
-    /**
+    /**
      * 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`"]
-    )
-    fun setVerbose(verbosity: BooleanArray) {
-        // 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 value in a single, central place,
-        // so we find the top-level command,
-        // and store the verbosity level on our top-level command's LoggingMixin.
-        (mixee.root().userObject() as MyApp).loggingMixin.verbosity = verbosity
-    }
-}
-
-@Command(name = "app", subcommands = [Sub::class])
-class MyApp : Runnable {
-    @Mixin
-    lateinit var loggingMixin: LoggingMixin
-    override fun run() {
-        logger.trace("Starting... (trace) from app")
-        logger.debug("Starting... (debug) from app")
-        logger.info ("Starting... (info)  from app")
-        logger.warn ("Starting... (warn)  from app")
-    }
-
-    private fun calcLogLevel(): Level {
-        return when (loggingMixin.verbosity.size) {
-            0 -> Level.WARN
-            1 -> Level.INFO
-            2 -> Level.DEBUG
-            else -> Level.TRACE
-        }
-    }
-
-    // A reference to this method can be used as a custom execution strategy
-    // that first configures Log4j based on the specified verbosity level,
-    // and then delegates to the default execution strategy.
-    private fun executionStrategy(parseResult: ParseResult): Int {
-        Configurator.setRootLevel(calcLogLevel()) // configure log4j
-        return RunLast().execute(parseResult) // default execution strategy
-    }
-
-    companion object {
-        private val logger: Logger = LogManager.getLogger(MyApp::class.java)
-        @JvmStatic
-        fun main(args: Array<String>) {
-            val app = MyApp()
-            CommandLine(app)
-                .setExecutionStrategy { parseResult: ParseResult -> app.executionStrategy(parseResult) }
-                .execute(*args)
-        }
-    }
-}
-
-@Command(name = "sub")
-class Sub : Runnable {
-    @Mixin
-    lateinit var loggingMixin: LoggingMixin
-    private val logger: Logger = LogManager.getLogger()
-
-    override fun run() {
-        logger.trace("Hi (tracing)   from app sub")
-        logger.debug("Hi (debugging) from app sub")
-        logger.info ("Hi (info)      from app sub")
-        logger.warn ("Hi (warning)   from app sub")
-    }
-
-    @Command
-    fun subsubmethod(@Mixin loggingMixin: LoggingMixin?) {
-        logger.trace("Hi (tracing)   from app sub subsubmethod")
-        logger.debug("Hi (debugging) from app sub subsubmethod")
-        logger.info ("Hi (info)      from app sub subsubmethod")
-        logger.warn ("Hi (warning)   from app sub subsubmethod")
-    }
-}
+ */ + @Option( + names = ["-v", "--verbose"], description = [ + "Specify multiple -v options to increase verbosity.", + "For example, `-v -v -v` or `-vvv`"] + ) + fun setVerbose(verbosity: BooleanArray) { + // 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 value in a single, central place, + // so we find the top-level command, + // and store the verbosity level on our top-level command's LoggingMixin. + (mixee.root().userObject() as MyApp).loggingMixin.verbosity = verbosity + } +} + +@Command(name = "app", subcommands = [Sub::class]) +class MyApp : Runnable { + @Mixin + lateinit var loggingMixin: LoggingMixin + override fun run() { + logger.trace("Starting... (trace) from app") + logger.debug("Starting... (debug) from app") + logger.info ("Starting... (info) from app") + logger.warn ("Starting... (warn) from app") + } + + private fun calcLogLevel(): Level { + return when (loggingMixin.verbosity.size) { + 0 -> Level.WARN + 1 -> Level.INFO + 2 -> Level.DEBUG + else -> Level.TRACE + } + } + + // A reference to this method can be used as a custom execution strategy + // that first configures Log4j based on the specified verbosity level, + // and then delegates to the default execution strategy. + private fun executionStrategy(parseResult: ParseResult): Int { + Configurator.setRootLevel(calcLogLevel()) // configure log4j + return RunLast().execute(parseResult) // default execution strategy + } + + companion object { + private val logger: Logger = LogManager.getLogger(MyApp::class.java) + @JvmStatic + fun main(args: Array<String>) { + val app = MyApp() + CommandLine(app) + .setExecutionStrategy { parseResult: ParseResult -> app.executionStrategy(parseResult) } + .execute(*args) + } + } +} + +@Command(name = "sub") +class Sub : Runnable { + @Mixin + lateinit var loggingMixin: LoggingMixin + private val logger: Logger = LogManager.getLogger() + + override fun run() { + logger.trace("Hi (tracing) from app sub") + logger.debug("Hi (debugging) from app sub") + logger.info ("Hi (info) from app sub") + logger.warn ("Hi (warning) from app sub") + } + + @Command + fun subsubmethod(@Mixin loggingMixin: LoggingMixin?) { + logger.trace("Hi (tracing) from app sub subsubmethod") + logger.debug("Hi (debugging) from app sub subsubmethod") + logger.info ("Hi (info) from app sub subsubmethod") + logger.warn ("Hi (warning) from app sub subsubmethod") + } +}
-
@Command(name = "i18n-demo", resourceBundle = "my.org.I18nDemo_Messages")
-class I18nDemo {}
+
@Command(name = "i18n-demo", resourceBundle = "my.org.I18nDemo_Messages")
+class I18nDemo {}
@@ -13784,19 +13509,19 @@

19.1. Confi
Java
-
@Command class I18nDemo2 {}
+
@Command class I18nDemo2 {}
 
-CommandLine cmd = new CommandLine(new I18nDemo2());
-cmd.setResourceBundle(ResourceBundle.getBundle("my.org.I18nDemo2_Messages"));
+CommandLine cmd = new CommandLine(new I18nDemo2()); +cmd.setResourceBundle(ResourceBundle.getBundle("my.org.I18nDemo2_Messages"));
Kotlin
-
@Command class I18nDemo2 {}
+
@Command class I18nDemo2 {}
 
-val cmd = CommandLine(I18nDemo2())
-cmd.resourceBundle = ResourceBundle.getBundle("my.org.I18nDemo2_Messages")
+val cmd = CommandLine(I18nDemo2()) +cmd.resourceBundle = ResourceBundle.getBundle("my.org.I18nDemo2_Messages")

@@ -13869,13 +13594,13 @@

Java
-
@Option(names = "-x", descriptionKey = "xoption") int x;
+
@Option(names = "-x", descriptionKey = "xoption") int x;
Kotlin
-
@Option(names = ["-x"], descriptionKey = "xoption") var x = 0
+
@Option(names = ["-x"], descriptionKey = "xoption") var x = 0
Kotlin
-
@Option(names = ["-v", "--verbose"]) lateinit var verbose: BooleanArray
+
@Option(names = ["-v", "--verbose"]) lateinit var verbose: BooleanArray
Kotlin
-
@Parameters(index = "0..*", paramLabel = "FILES") lateinit var files: Array<File>
+
@Parameters(index = "0..*", paramLabel = "FILES") lateinit var files: Array<File>
Kotlin
-
@ArgGroup(headingKey = "myBundleKey") lateinit var myGroup: MyArgGroup
+
@ArgGroup(headingKey = "myBundleKey") lateinit var myGroup: MyArgGroup
@@ -14037,79 +13762,79 @@

Java
-
class InitLocale {
-    @Option(names = { "-l", "--locale" }, description = "locale for message texts (phase 1)")
-    void setLocale(String locale) {
-        Locale.setDefault(new Locale(locale));
-    }
+
class InitLocale {
+    @Option(names = { "-l", "--locale" }, description = "locale for message texts (phase 1)")
+    void setLocale(String locale) {
+        Locale.setDefault(new Locale(locale));
+    }
 
-    @Unmatched
-    List<String> remainder; // ignore any other parameters and options in the first parsing phase
-}
+    @Unmatched
+    List<String> remainder; // ignore any other parameters and options in the first parsing phase
+}
 
-@Command(name = "GreetingApp", resourceBundle = "mybundle", mixinStandardHelpOptions = true)
-public class GreetingApp implements Runnable {
-    @Option(names = { "-l", "--locale" }, paramLabel = "<locale>")
-    private String ignored;
+@Command(name = "GreetingApp", resourceBundle = "mybundle", mixinStandardHelpOptions = true)
+public class GreetingApp implements Runnable {
+    @Option(names = { "-l", "--locale" }, paramLabel = "<locale>")
+    private String ignored;
 
-    @Parameters(arity = "1..", paramLabel = "<name1> <name2>")
-    private String[] names;
+    @Parameters(arity = "1..", paramLabel = "<name1> <name2>")
+    private String[] names;
 
-    ResourceBundle bundle = ResourceBundle.getBundle("mybundle");
+    ResourceBundle bundle = ResourceBundle.getBundle("mybundle");
 
-    public void run() { // business logic here
-        for (String name : names) {
-            System.out.println(MessageFormat.format(bundle.getString("Hello"), name));
-        }
-    }
+    public void run() { // business logic here
+        for (String name : names) {
+            System.out.println(MessageFormat.format(bundle.getString("Hello"), name));
+        }
+    }
 
-    public static void main(String[] args) {
-        // first phase: configure locale
-        new CommandLine(new InitLocale()).parseArgs(args);
+    public static void main(String[] args) {
+        // first phase: configure locale
+        new CommandLine(new InitLocale()).parseArgs(args);
 
-        // second phase: parse all args (ignoring --locale) and run the app
-        new CommandLine(new GreetingApp()).execute(args);
-    }
-}
+ // second phase: parse all args (ignoring --locale) and run the app + new CommandLine(new GreetingApp()).execute(args); + } +}

Kotlin
-
class InitLocale {
-    @Option(names = ["-l", "--locale"], description = ["locale for message texts (phase 1)"])
-    fun setLocale(locale: String?) {
-        Locale.setDefault(Locale(locale))
-    }
+
class InitLocale {
+    @Option(names = ["-l", "--locale"], description = ["locale for message texts (phase 1)"])
+    fun setLocale(locale: String?) {
+        Locale.setDefault(Locale(locale))
+    }
 
-    @Unmatched
-    lateinit var others : List<String> // ignore other parameters/options in first parsing phase
-}
+    @Unmatched
+    lateinit var others : List<String> // ignore other parameters/options in first parsing phase
+}
 
-@Command(name = "GreetingApp", resourceBundle = "mybundle", mixinStandardHelpOptions = true)
-class GreetingApp : Runnable {
-    @Option(names = ["-l", "--locale"], paramLabel = "<locale>")
-    lateinit var ignored: String
+@Command(name = "GreetingApp", resourceBundle = "mybundle", mixinStandardHelpOptions = true)
+class GreetingApp : Runnable {
+    @Option(names = ["-l", "--locale"], paramLabel = "<locale>")
+    lateinit var ignored: String
 
-    @Parameters(arity = "1..", paramLabel = "<name1> <name2>")
-    lateinit var names: Array<String>
+    @Parameters(arity = "1..", paramLabel = "<name1> <name2>")
+    lateinit var names: Array<String>
 
-    private var bundle = ResourceBundle.getBundle("mybundle")
+    private var bundle = ResourceBundle.getBundle("mybundle")
 
-    override fun run() { // business logic here
-        names.onEach {
-            println(MessageFormat.format(bundle.getString("Hello"), it))
-        }
-    }
-}
+    override fun run() { // business logic here
+        names.onEach {
+            println(MessageFormat.format(bundle.getString("Hello"), it))
+        }
+    }
+}
 
-fun main(args: Array<String>)  {
-    // first phase: configure locale
-    CommandLine(picocli.examples.kotlin.i18n.localecontrol.InitLocale()).parseArgs(*args)
+fun main(args: Array<String>)  {
+    // first phase: configure locale
+    CommandLine(picocli.examples.kotlin.i18n.localecontrol.InitLocale()).parseArgs(*args)
 
-    // second phase: parse all args (ignoring --locale) and run the app
-    exitProcess(CommandLine(GreetingApp()).execute(*args))
-}
+ // second phase: parse all args (ignoring --locale) and run the app + exitProcess(CommandLine(GreetingApp()).execute(*args)) +}
@@ -14179,46 +13904,46 @@

Java
-
@Command(name = "status", mixinStandardHelpOptions = true,
-         description = "This command logs the ${COMMAND-NAME} for ${PARENT-COMMAND-NAME}.",
-         version = {
-            "Versioned Command 1.0",
-            "Picocli " + picocli.CommandLine.VERSION,
-            "JVM: ${java.version} (${java.vendor} ${java.vm.name} ${java.vm.version})",
-            "OS: ${os.name} ${os.version} ${os.arch}"})
-class Status {
-    // -d or --directories
-    @Option(names = {"${dirOptionName1:--d}", "${dirOptionName2:---directories}"},
-            description = {"Specify one or more directories, " +
-                               "separated by '${sys:path.separator}'.",
-                           "The default is the user home directory (${DEFAULT-VALUE})."},
-            arity = "${sys:dirOptionArity:-1..*}",
-            defaultValue = "${sys:user.home}",
-            split = "${sys:path.separator}")
-    String[] directories;
-}
+
@Command(name = "status", mixinStandardHelpOptions = true,
+         description = "This command logs the ${COMMAND-NAME} for ${PARENT-COMMAND-NAME}.",
+         version = {
+            "Versioned Command 1.0",
+            "Picocli " + picocli.CommandLine.VERSION,
+            "JVM: ${java.version} (${java.vendor} ${java.vm.name} ${java.vm.version})",
+            "OS: ${os.name} ${os.version} ${os.arch}"})
+class Status {
+    // -d or --directories
+    @Option(names = {"${dirOptionName1:--d}", "${dirOptionName2:---directories}"},
+            description = {"Specify one or more directories, " +
+                               "separated by '${sys:path.separator}'.",
+                           "The default is the user home directory (${DEFAULT-VALUE})."},
+            arity = "${sys:dirOptionArity:-1..*}",
+            defaultValue = "${sys:user.home}",
+            split = "${sys:path.separator}")
+    String[] directories;
+}

Kotlin
-
@Command(name = "status", mixinStandardHelpOptions = true,
-         description = ["This command logs the \${COMMAND-NAME} for \${PARENT-COMMAND-NAME}."],
-         version = ["Versioned Command 1.0",
-                    "Picocli $VERSION",
-                    "JVM: \${java.version} (\${java.vendor} \${java.vm.name} \${java.vm.version})",
-                    "OS: \${os.name} \${os.version} \${os.arch}"])
-class Status {
-    // -d or --directories
-    @Option(names = ["\${dirOptionName1:--d}", "\${dirOptionName2:---directories}"],
-            description = ["Specify one or more directories, " +
-                                "separated by '\${sys:path.separator}'.",
-                           "The default is the user home directory (\${DEFAULT-VALUE})."],
-        arity = "\${sys:dirOptionArity:-1..*}",
-        defaultValue = "\${sys:user.home}",
-        split = "\${sys:path.separator}")
-    lateinit var directories: Array<String>
-}
+
@Command(name = "status", mixinStandardHelpOptions = true,
+         description = ["This command logs the \${COMMAND-NAME} for \${PARENT-COMMAND-NAME}."],
+         version = ["Versioned Command 1.0",
+                    "Picocli $VERSION",
+                    "JVM: \${java.version} (\${java.vendor} \${java.vm.name} \${java.vm.version})",
+                    "OS: \${os.name} \${os.version} \${os.arch}"])
+class Status {
+    // -d or --directories
+    @Option(names = ["\${dirOptionName1:--d}", "\${dirOptionName2:---directories}"],
+            description = ["Specify one or more directories, " +
+                                "separated by '\${sys:path.separator}'.",
+                           "The default is the user home directory (\${DEFAULT-VALUE})."],
+        arity = "\${sys:dirOptionArity:-1..*}",
+        defaultValue = "\${sys:user.home}",
+        split = "\${sys:path.separator}")
+    lateinit var directories: Array<String>
+}
Kotlin
-
interface Counter {
-    @get:Option(names = ["--count"])
-    val count: Int
-}
+
interface Counter {
+    @get:Option(names = ["--count"])
+    val count: Int
+}
Kotlin
-
val cmd = CommandLine(Counter::class.java) // specify a class
-val args = arrayOf("--count", "3")
-cmd.parseArgs(*args)
-val counter: Counter = cmd.getCommand() // picocli created an instance
-assertEquals(3, counter.count) // method returns command line value
+
val cmd = CommandLine(Counter::class.java) // specify a class
+val args = arrayOf("--count", "3")
+cmd.parseArgs(*args)
+val counter: Counter = cmd.getCommand() // picocli created an instance
+assertEquals(3, counter.count) // method returns command line value
@@ -14491,28 +14216,28 @@

Java
-
class Counter {
-    int count;
+
class Counter {
+    int count;
 
-    @Option(names = "--count")
-    void setCount(int count) {
-        this.count = count;
-    }
-}
+ @Option(names = "--count") + void setCount(int count) { + this.count = count; + } +}
Kotlin
-
class Counter {
-    var count = 0
+
class Counter {
+    var count = 0
 
-    @JvmName("setCount1")
-    @Option(names = ["--count"])
-    fun setCount(count: Int) {
-        this.count = count
-    }
-}
+ @JvmName("setCount1") + @Option(names = ["--count"]) + fun setCount(count: Int) { + this.count = count + } +}
Kotlin
-
val counter = Counter() // the instance to populate
-val cmd = CommandLine(counter)
-val args = arrayOf("--count", "3")
-cmd.parseArgs(*args)
-assertEquals(3, counter.count) // method was invoked with command line value
+
val counter = Counter() // the instance to populate
+val cmd = CommandLine(counter)
+val args = arrayOf("--count", "3")
+cmd.parseArgs(*args)
+assertEquals(3, counter.count) // method was invoked with command line value
@@ -14544,58 +14269,58 @@

Java
-
class ValidationExample {
-    private Map<String, String> properties = new LinkedHashMap<>();
+
class ValidationExample {
+    private Map<String, String> properties = new LinkedHashMap<>();
 
-    @Spec private CommandSpec spec; // injected by picocli
+    @Spec private CommandSpec spec; // injected by picocli
 
-    @Option(names = {"-D", "--property"}, paramLabel = "KEY=VALUE")
-    public void setProperty(Map<String, String> map) {
-        for (String key : map.keySet()) {
-            String newValue = map.get(key);
-            validateUnique(key, newValue);
-            properties.put(key, newValue);
-        }
-    }
+    @Option(names = {"-D", "--property"}, paramLabel = "KEY=VALUE")
+    public void setProperty(Map<String, String> map) {
+        for (String key : map.keySet()) {
+            String newValue = map.get(key);
+            validateUnique(key, newValue);
+            properties.put(key, newValue);
+        }
+    }
 
-    private void validateUnique(String key, String newValue) {
-        String existing = properties.get(key);
-        if (existing != null && !existing.equals(newValue)) {
-            throw new ParameterException(spec.commandLine(),
-                    String.format("Duplicate key '%s' for values '%s' and '%s'.",
-                    key, existing, newValue));
-        }
-    }
-    // ...
-}
+ private void validateUnique(String key, String newValue) { + String existing = properties.get(key); + if (existing != null && !existing.equals(newValue)) { + throw new ParameterException(spec.commandLine(), + String.format("Duplicate key '%s' for values '%s' and '%s'.", + key, existing, newValue)); + } + } + // ... +}

Kotlin
-
class ValidationExample : Runnable {
-    private val properties: MutableMap<String, String?> = LinkedHashMap()
+
class ValidationExample : Runnable {
+    private val properties: MutableMap<String, String?> = LinkedHashMap()
 
-    @Spec private lateinit var spec : CommandSpec // injected by picocli
+    @Spec private lateinit var spec : CommandSpec // injected by picocli
 
-    @Option(names = ["-D", "--property"], paramLabel = "KEY=VALUE")
-    fun setProperty(map: Map<String, String>) {
-        for (key in map.keys) {
-            val newValue = map[key]
-            validateUnique(key, newValue)
-            properties[key] = newValue
-        }
-    }
+    @Option(names = ["-D", "--property"], paramLabel = "KEY=VALUE")
+    fun setProperty(map: Map<String, String>) {
+        for (key in map.keys) {
+            val newValue = map[key]
+            validateUnique(key, newValue)
+            properties[key] = newValue
+        }
+    }
 
-    private fun validateUnique(key: String, newValue: String?) {
-        val existing = properties[key]
-        if (existing != null && existing != newValue) {
-            throw ParameterException(spec.commandLine(),
-                "Duplicate key '$key' for values '$existing' and '$newValue'.")
-        }
-    }
-    // ...
-}
+ private fun validateUnique(key: String, newValue: String?) { + val existing = properties[key] + if (existing != null && existing != newValue) { + throw ParameterException(spec.commandLine(), + "Duplicate key '$key' for values '$existing' and '$newValue'.") + } + } + // ... +}
@@ -14609,45 +14334,45 @@

21.3.
Java
-
class Cat {
-    public static void main(String[] args) {
-        Method doit = CommandLine.getCommandMethods(Cat.class, "cat").get(0);
-        CommandLine cmd = new CommandLine(doit);
-        int exitCode = cmd.execute(args);
-    }
-
-    @Command(description = "Concatenate FILE(s) to standard output.",
-             mixinStandardHelpOptions = true, version = "4.1.3")
-    void cat(@Option(names = {"-E", "--show-ends"}) boolean showEnds,
-             @Option(names = {"-n", "--number"}) boolean number,
-             @Option(names = {"-T", "--show-tabs"}) boolean showTabs,
-             @Option(names = {"-v", "--show-nonprinting"}) boolean showNonPrinting,
-             @Parameters(paramLabel = "FILE") File[] files) {
-        // process files
-    }
-}
+
class Cat {
+    public static void main(String[] args) {
+        Method doit = CommandLine.getCommandMethods(Cat.class, "cat").get(0);
+        CommandLine cmd = new CommandLine(doit);
+        int exitCode = cmd.execute(args);
+    }
+
+    @Command(description = "Concatenate FILE(s) to standard output.",
+             mixinStandardHelpOptions = true, version = "4.1.3")
+    void cat(@Option(names = {"-E", "--show-ends"}) boolean showEnds,
+             @Option(names = {"-n", "--number"}) boolean number,
+             @Option(names = {"-T", "--show-tabs"}) boolean showTabs,
+             @Option(names = {"-v", "--show-nonprinting"}) boolean showNonPrinting,
+             @Parameters(paramLabel = "FILE") File[] files) {
+        // process files
+    }
+}
Kotlin
-
class Cat {
-    @Command(description = ["Concatenate FILE(s) to standard output."],
-             mixinStandardHelpOptions = true, version = ["4.1.3"])
-    fun cat(@Option(names = ["-E", "--show-ends"]) showEnds: Boolean,
-            @Option(names = ["-n", "--number"]) number: Boolean,
-            @Option(names = ["-T", "--show-tabs"]) showTabs: Boolean,
-            @Option(names = ["-v", "--show-nonprinting"]) showNonPrinting: Boolean,
-            @Parameters(paramLabel = "FILE") files: Array<File>?) {
-        // process files
-    }
-}
+
class Cat {
+    @Command(description = ["Concatenate FILE(s) to standard output."],
+             mixinStandardHelpOptions = true, version = ["4.1.3"])
+    fun cat(@Option(names = ["-E", "--show-ends"]) showEnds: Boolean,
+            @Option(names = ["-n", "--number"]) number: Boolean,
+            @Option(names = ["-T", "--show-tabs"]) showTabs: Boolean,
+            @Option(names = ["-v", "--show-nonprinting"]) showNonPrinting: Boolean,
+            @Parameters(paramLabel = "FILE") files: Array<File>?) {
+        // process files
+    }
+}
 
-fun main(args: Array<String>) {
-    val doit: Method = CommandLine.getCommandMethods(Cat::class.java, "cat")[0]
-    val cmd = CommandLine(doit)
-    val exitCode = cmd.execute(*args)
-}
+fun main(args: Array<String>) { + val doit: Method = CommandLine.getCommandMethods(Cat::class.java, "cat")[0] + val cmd = CommandLine(doit) + val exitCode = cmd.execute(*args) +}
@@ -14693,37 +14418,37 @@

2
Java
-
@Command(name = "git", mixinStandardHelpOptions = true, version = "picocli-4.1.3",
-         resourceBundle = "Git_Messages", subcommands = { HelpCommand.class })
-class Git {
-    @Option(names = "--git-dir", descriptionKey = "GITDIR")
-    Path path;
-
-    @Command
-    void commit(@Option(names = {"-m", "--message"}) String commitMessage,
-                @Option(names = "--squash", paramLabel = "<commit>") String squash,
-                @Parameters(paramLabel = "<file>") File[] files) {
-        // ... implement business logic
-    }
-}
+
@Command(name = "git", mixinStandardHelpOptions = true, version = "picocli-4.1.3",
+         resourceBundle = "Git_Messages", subcommands = { HelpCommand.class })
+class Git {
+    @Option(names = "--git-dir", descriptionKey = "GITDIR")
+    Path path;
+
+    @Command
+    void commit(@Option(names = {"-m", "--message"}) String commitMessage,
+                @Option(names = "--squash", paramLabel = "<commit>") String squash,
+                @Parameters(paramLabel = "<file>") File[] files) {
+        // ... implement business logic
+    }
+}
Kotlin
-
@Command(name = "git", mixinStandardHelpOptions = true, version = ["picocli-4.1.3"],
-         resourceBundle = "Git_Messages", subcommands = [HelpCommand::class])
-class Git {
-    @Option(names = ["--git-dir"], descriptionKey = "GITDIR")
-    lateinit var path: Path
-
-    @Command
-    fun commit(@Option(names = ["-m", "--message"]) commitMessage: String?,
-               @Option(names = ["--squash"], paramLabel = "<commit>") squash: String?,
-               @Parameters(paramLabel = "<file>") files: Array<File?>?) {
-        // ... implement business logic
-    }
-}
+
@Command(name = "git", mixinStandardHelpOptions = true, version = ["picocli-4.1.3"],
+         resourceBundle = "Git_Messages", subcommands = [HelpCommand::class])
+class Git {
+    @Option(names = ["--git-dir"], descriptionKey = "GITDIR")
+    lateinit var path: Path
+
+    @Command
+    fun commit(@Option(names = ["-m", "--message"]) commitMessage: String?,
+               @Option(names = ["--squash"], paramLabel = "<commit>") squash: String?,
+               @Parameters(paramLabel = "<file>") files: Array<File?>?) {
+        // ... implement business logic
+    }
+}
Kotlin
-
class CommonParams {
-    @Option(names = ["-x"]) var x = 0
-    @Option(names = ["-y"]) var y = 0
-}
+
class CommonParams {
+    @Option(names = ["-x"]) var x = 0
+    @Option(names = ["-y"]) var y = 0
+}
 
-@Command
-class App {
-    @Command
-    fun doit(@Mixin params: CommonParams?, @Option(names = ["-z"]) z: Int) {}
-}
+@Command +class App { + @Command + fun doit(@Mixin params: CommonParams?, @Option(names = ["-z"]) z: Int) {} +}
Kotlin
-
@Command
-class InjectSpecExample : Runnable {
-    @Spec lateinit var commandSpec: CommandSpec
-    //...
+
@Command
+class InjectSpecExample : Runnable {
+    @Spec lateinit var commandSpec: CommandSpec
+    //...
 
-    override fun run() {
-        // do something with the injected spec
-        println("My full name is ${commandSpec.qualifiedName()}")
-    }
-}
+ override fun run() { + // do something with the injected spec + println("My full name is ${commandSpec.qualifiedName()}") + } +}
@@ -14893,15 +14618,15 @@

21.5. Cus
Java
-
IFactory myFactory = getCustomFactory();
-CommandLine cmdLine = new CommandLine(new Git(), myFactory);
+
IFactory myFactory = getCustomFactory();
+CommandLine cmdLine = new CommandLine(new Git(), myFactory);
Kotlin
-
val myFactory: IFactory = getCustomFactory()
-val cmdLine = CommandLine(Git(), myFactory)
+
val myFactory: IFactory = getCustomFactory()
+val cmdLine = CommandLine(Git(), myFactory)
@@ -14909,16 +14634,16 @@

21.5. Cus

-
public interface IFactory {
-    /**
+
public interface IFactory {
+    /**
      * Creates and returns an instance of the specified class.
      * @param clazz the class to instantiate
      * @param <K> the type to instantiate
      * @return the new instance
      * @throws Exception an exception detailing what went wrong when creating the instance
-     */
-    <K> K create(Class<K> clazz) throws Exception;
-}
+ */ + <K> K create(Class<K> clazz) throws Exception; +}
@@ -14934,26 +14659,26 @@

21.5. Cus
Java
-
@Override
-public <K> K create(Class<K> clazz) throws Exception {
-    try {
-        return doCreate(clazz); // custom factory lookup or instantiation
-    } catch (Exception e) {
-        return CommandLine.defaultFactory().create(clazz); // fallback if missing
-    }
-}
+
@Override
+public <K> K create(Class<K> clazz) throws Exception {
+    try {
+        return doCreate(clazz); // custom factory lookup or instantiation
+    } catch (Exception e) {
+        return CommandLine.defaultFactory().create(clazz); // fallback if missing
+    }
+}
Kotlin
-
override fun <K : Any> create(clazz: Class<K>): K {
-    return try {
-        doCreate(clazz) // custom factory lookup or instantiation
-    } catch (e: Exception) {
-        CommandLine.defaultFactory().create(clazz) // fallback if missing
-    }
-}
+
override fun <K : Any> create(clazz: Class<K>): K {
+    return try {
+        doCreate(clazz) // custom factory lookup or instantiation
+    } catch (e: Exception) {
+        CommandLine.defaultFactory().create(clazz) // fallback if missing
+    }
+}

@@ -14965,8 +14690,8 @@

Kotlin
-
@Command(modelTransformer = Dynamic.SubCmdFilter::class)
-class Dynamic {
+
@Command(modelTransformer = Dynamic.SubCmdFilter::class)
+class Dynamic {
 
-    class SubCmdFilter : CommandLine.IModelTransformer {
-        override fun transform(commandSpec: CommandSpec): CommandSpec {
-            if (Boolean.getBoolean("disable_sub")) {
-                commandSpec.removeSubcommand("sub")
-            }
-            return commandSpec
-        }
-    }
+    class SubCmdFilter : CommandLine.IModelTransformer {
+        override fun transform(commandSpec: CommandSpec): CommandSpec {
+            if (Boolean.getBoolean("disable_sub")) {
+                commandSpec.removeSubcommand("sub")
+            }
+            return commandSpec
+        }
+    }
 
-    @Command
-    private fun sub() {
-        // subcommand, business logic
-    }
-}
+ @Command + private fun sub() { + // subcommand, business logic + } +}
@@ -15070,27 +14795,27 @@

21.
Java
-
class AutomaticIndex {
-    @Parameters(hidden = true)   // "hidden": don't show this parameter in usage help message
-    List<String> allParameters;  // no "index" attribute: captures _all_ arguments
+
class AutomaticIndex {
+    @Parameters(hidden = true)   // "hidden": don't show this parameter in usage help message
+    List<String> allParameters;  // no "index" attribute: captures _all_ arguments
 
-    @Parameters String group;    // assigned index = "0"
-    @Parameters String artifact; // assigned index = "1"
-    @Parameters String version;  // assigned index = "2"
-}
+ @Parameters String group; // assigned index = "0" + @Parameters String artifact; // assigned index = "1" + @Parameters String version; // assigned index = "2" +}
Kotlin
-
class AutomaticIndex {
-    @Parameters(hidden = true)  // "hidden": don't show this parameter in usage help message
-    lateinit var allParameters: List<String>   // no "index" attribute: captures _all_ arguments
+
class AutomaticIndex {
+    @Parameters(hidden = true)  // "hidden": don't show this parameter in usage help message
+    lateinit var allParameters: List<String>   // no "index" attribute: captures _all_ arguments
 
-    @Parameters lateinit var group:    String  // assigned index = "0"
-    @Parameters lateinit var artifact: String  // assigned index = "1"
-    @Parameters lateinit var version:  String  // assigned index = "2"
-}
+ @Parameters lateinit var group: String // assigned index = "0" + @Parameters lateinit var artifact: String // assigned index = "1" + @Parameters lateinit var version: String // assigned index = "2" +}
@@ -15099,25 +14824,25 @@

21.
Java
-
String[] args = { "info.picocli", "picocli", "4.3.0" };
-AutomaticIndex auto = CommandLine.populateCommand(new AutomaticIndex(), args);
+
String[] args = { "info.picocli", "picocli", "4.3.0" };
+AutomaticIndex auto = CommandLine.populateCommand(new AutomaticIndex(), args);
 
-assert auto.group.equals("info.picocli");
-assert auto.artifact.equals("picocli");
-assert auto.version.equals("4.3.0");
-assert auto.allParameters.equals(Arrays.asList(args));
+assert auto.group.equals("info.picocli"); +assert auto.artifact.equals("picocli"); +assert auto.version.equals("4.3.0"); +assert auto.allParameters.equals(Arrays.asList(args));
Kotlin
-
val args = arrayOf("info.picocli", "picocli", "4.3.0")
-val auto = CommandLine.populateCommand(AutomaticIndex(), *args)
+
val args = arrayOf("info.picocli", "picocli", "4.3.0")
+val auto = CommandLine.populateCommand(AutomaticIndex(), *args)
 
-assertEquals("info.picocli", auto.group )
-assertEquals("picocli", auto.artifact)
-assertEquals("4.3.0", auto.version)
-assertEquals(Arrays.asList(*args), auto.allParameters)
+assertEquals("info.picocli", auto.group ) +assertEquals("picocli", auto.artifact) +assertEquals("4.3.0", auto.version) +assertEquals(Arrays.asList(*args), auto.allParameters)
Kotlin
-
class Anchored {
-    @Parameters(index = "1+") lateinit var p1: String  // assigned index = "1" or higher
-    @Parameters(index = "1+") lateinit var p2: String  // assigned index = "2" or higher
-}
+
class Anchored {
+    @Parameters(index = "1+") lateinit var p1: String  // assigned index = "1" or higher
+    @Parameters(index = "1+") lateinit var p2: String  // assigned index = "2" or higher
+}

@@ -15192,36 +14917,36 @@

Java
-
class ExplicitAndAutomaticIndexes {
-    @Parameters(index = "0" ) String explicit0;  // explicit index "0" at default anchor point
-    @Parameters String pAuto1;                   // assigned index "1", anchor point + 1
-    @Parameters String pAuto2;                   // assigned index "2"
-    @Parameters(index = "1+") String pAnchored1; // assigned index "1": no explicit index 1
-    @Parameters(index = "1+") String pAnchored2; // assigned index "2"
-    @Parameters(index = "2" ) String explicit2;  // explicit index "2", matching anchor for "2+"
-    @Parameters(index = "2+") String pAnchored3; // assigned index "3", anchor point + 1
-    @Parameters(index = "2+") String pAnchored4; // assigned index "4"
-}
+
class ExplicitAndAutomaticIndexes {
+    @Parameters(index = "0" ) String explicit0;  // explicit index "0" at default anchor point
+    @Parameters String pAuto1;                   // assigned index "1", anchor point + 1
+    @Parameters String pAuto2;                   // assigned index "2"
+    @Parameters(index = "1+") String pAnchored1; // assigned index "1": no explicit index 1
+    @Parameters(index = "1+") String pAnchored2; // assigned index "2"
+    @Parameters(index = "2" ) String explicit2;  // explicit index "2", matching anchor for "2+"
+    @Parameters(index = "2+") String pAnchored3; // assigned index "3", anchor point + 1
+    @Parameters(index = "2+") String pAnchored4; // assigned index "4"
+}

Kotlin
-
class ExplicitAndAutomaticIndexes {
-    @Parameters(index = "0") lateinit var explicit0: String   // explicit index "0"
-                                                              // at default anchor point
-    @Parameters lateinit var pAuto1: String                   // assigned index "1",
-                                                              // anchor point + 1
-    @Parameters lateinit var pAuto2: String                   // assigned index "2"
-    @Parameters(index = "1+") lateinit var pAnchored1: String // assigned index "1":
-                                                              // no explicit index 1
-    @Parameters(index = "1+") lateinit var pAnchored2: String // assigned index "2"
-    @Parameters(index = "2") lateinit var explicit2: String   // explicit index "2",
-                                                              // matching anchor for "2+"
-    @Parameters(index = "2+") lateinit var pAnchored3: String // assigned index "3",
-                                                              // anchor point + 1
-    @Parameters(index = "2+") lateinit var pAnchored4: String // assigned index "4"
-}
+
class ExplicitAndAutomaticIndexes {
+    @Parameters(index = "0") lateinit var explicit0: String   // explicit index "0"
+                                                              // at default anchor point
+    @Parameters lateinit var pAuto1: String                   // assigned index "1",
+                                                              // anchor point + 1
+    @Parameters lateinit var pAuto2: String                   // assigned index "2"
+    @Parameters(index = "1+") lateinit var pAnchored1: String // assigned index "1":
+                                                              // no explicit index 1
+    @Parameters(index = "1+") lateinit var pAnchored2: String // assigned index "2"
+    @Parameters(index = "2") lateinit var explicit2: String   // explicit index "2",
+                                                              // matching anchor for "2+"
+    @Parameters(index = "2+") lateinit var pAnchored3: String // assigned index "3",
+                                                              // anchor point + 1
+    @Parameters(index = "2+") lateinit var pAnchored4: String // assigned index "4"
+}

@@ -15238,27 +14963,27 @@

Java
-
class Unanchored {
-    @Parameters(index = "0" ) String p0;
-    @Parameters(index = "1+") String p1; // assigned index = "1"
-    @Parameters(index = "1+") String p2; // assigned index = "2"
-    @Parameters(index = "3" ) String p3;
-    @Parameters(index = "+" ) String p4; // assigned index = "4" <-- unanchored
-    @Parameters(index = "+" ) String p5; // assigned index = "5" <-- unanchored
-}
+
class Unanchored {
+    @Parameters(index = "0" ) String p0;
+    @Parameters(index = "1+") String p1; // assigned index = "1"
+    @Parameters(index = "1+") String p2; // assigned index = "2"
+    @Parameters(index = "3" ) String p3;
+    @Parameters(index = "+" ) String p4; // assigned index = "4" <-- unanchored
+    @Parameters(index = "+" ) String p5; // assigned index = "5" <-- unanchored
+}

Kotlin
-
class Unanchored {
-    @Parameters(index = "0" ) lateinit var p0: String
-    @Parameters(index = "1+") lateinit var p1: String  // assigned index = "1"
-    @Parameters(index = "1+") lateinit var p2: String  // assigned index = "2"
-    @Parameters(index = "3" ) lateinit var p3: String
-    @Parameters(index = "+" ) lateinit var p4: String  // assigned index = "4" <-- unanchored
-    @Parameters(index = "+" ) lateinit var p5: String  // assigned index = "5" <-- unanchored
-}
+
class Unanchored {
+    @Parameters(index = "0" ) lateinit var p0: String
+    @Parameters(index = "1+") lateinit var p1: String  // assigned index = "1"
+    @Parameters(index = "1+") lateinit var p2: String  // assigned index = "2"
+    @Parameters(index = "3" ) lateinit var p3: String
+    @Parameters(index = "+" ) lateinit var p4: String  // assigned index = "4" <-- unanchored
+    @Parameters(index = "+" ) lateinit var p5: String  // assigned index = "5" <-- unanchored
+}
@@ -15274,19 +14999,19 @@

Java
-
class BadCombination {
-    @Parameters(index = "0..*") List<String> all;
-    @Parameters(index = "+"   ) String last;
-}
+
class BadCombination {
+    @Parameters(index = "0..*") List<String> all;
+    @Parameters(index = "+"   ) String last;
+}
Kotlin
-
class BadCombination {
-    @Parameters(index = "0..*") lateinit var all: List<String>
-    @Parameters(index = "+"   ) lateinit var last: String
-}
+
class BadCombination {
+    @Parameters(index = "0..*") lateinit var all: List<String>
+    @Parameters(index = "+"   ) lateinit var last: String
+}
@@ -15316,25 +15041,25 @@

Java
-
class BooleanOptionWithParameters {
-    @Option(names = "-x", arity = "1", description = "1 mandatory parameter")
-    boolean x;
+
class BooleanOptionWithParameters {
+    @Option(names = "-x", arity = "1", description = "1 mandatory parameter")
+    boolean x;
 
-    @Option(names = "-y", arity = "0..1", description = "min 0 and max 1 parameter")
-    boolean y;
-}
+ @Option(names = "-y", arity = "0..1", description = "min 0 and max 1 parameter") + boolean y; +}
Kotlin
-
class BooleanOptionWithParameters {
-    @Option(names = ["-x"], arity = "1", description = ["1 mandatory parameter"])
-    var x = false
+
class BooleanOptionWithParameters {
+    @Option(names = ["-x"], arity = "1", description = ["1 mandatory parameter"])
+    var x = false
 
-    @Option(names = ["-y"], arity = "0..1", description = ["min 0 and max 1 parameter"])
-    var y = false
-}
+ @Option(names = ["-y"], arity = "0..1", description = ["min 0 and max 1 parameter"]) + var y = false +}
@@ -15375,55 +15100,55 @@

2
Java 8
-
new CommandLine(obj)
-        .registerConverter(Byte.class,    Byte::decode)
-        .registerConverter(Byte.TYPE,     Byte::decode)
-        .registerConverter(Short.class,   Short::decode)
-        .registerConverter(Short.TYPE,    Short::decode)
-        .registerConverter(Integer.class, Integer::decode)
-        .registerConverter(Integer.TYPE,  Integer::decode)
-        .registerConverter(Long.class,    Long::decode)
-        .registerConverter(Long.TYPE,     Long::decode);
+
new CommandLine(obj)
+        .registerConverter(Byte.class,    Byte::decode)
+        .registerConverter(Byte.TYPE,     Byte::decode)
+        .registerConverter(Short.class,   Short::decode)
+        .registerConverter(Short.TYPE,    Short::decode)
+        .registerConverter(Integer.class, Integer::decode)
+        .registerConverter(Integer.TYPE,  Integer::decode)
+        .registerConverter(Long.class,    Long::decode)
+        .registerConverter(Long.TYPE,     Long::decode);
Kotlin
-
CommandLine(obj)
-        .registerConverter(Byte::class.java,     java.lang.Byte::decode)
-        .registerConverter(java.lang.Byte.TYPE,  java.lang.Byte::decode)
-        .registerConverter(Short::class.java,    java.lang.Short::decode)
-        .registerConverter(java.lang.Short.TYPE, java.lang.Short::decode)
-        .registerConverter(Int::class.java,      Integer::decode)
-        .registerConverter(Integer.TYPE,         Integer::decode)
-        .registerConverter(Long::class.java,     java.lang.Long::decode)
-        .registerConverter(java.lang.Long.TYPE,  java.lang.Long::decode)
+
CommandLine(obj)
+        .registerConverter(Byte::class.java,     java.lang.Byte::decode)
+        .registerConverter(java.lang.Byte.TYPE,  java.lang.Byte::decode)
+        .registerConverter(Short::class.java,    java.lang.Short::decode)
+        .registerConverter(java.lang.Short.TYPE, java.lang.Short::decode)
+        .registerConverter(Int::class.java,      Integer::decode)
+        .registerConverter(Integer.TYPE,         Integer::decode)
+        .registerConverter(Long::class.java,     java.lang.Long::decode)
+        .registerConverter(java.lang.Long.TYPE,  java.lang.Long::decode)
Java 5
-
ITypeConverter<Integer> intConverter = new ITypeConverter<Integer>() {
-    public Integer convert(String s) {
-        return Integer.decode(s);
-    }
-};
-commandLine.registerConverter(Integer.class, intConverter);
-commandLine.registerConverter(Integer.TYPE,  intConverter);
-// ...
+
ITypeConverter<Integer> intConverter = new ITypeConverter<Integer>() {
+    public Integer convert(String s) {
+        return Integer.decode(s);
+    }
+};
+commandLine.registerConverter(Integer.class, intConverter);
+commandLine.registerConverter(Integer.TYPE,  intConverter);
+// ...
Kotlin
-
var intConverter: ITypeConverter<Int> = object : ITypeConverter<Int> {
-    override fun convert(s: String): Int {
-        return Integer.decode(s)
-    }
-}
-commandLine.registerConverter(Int::class.java, intConverter)
-commandLine.registerConverter(Integer.TYPE,    intConverter)
-// ...
+
var intConverter: ITypeConverter<Int> = object : ITypeConverter<Int> {
+    override fun convert(s: String): Int {
+        return Integer.decode(s)
+    }
+}
+commandLine.registerConverter(Int::class.java, intConverter)
+commandLine.registerConverter(Integer.TYPE,    intConverter)
+// ...

@@ -15439,9 +15164,9 @@

2
-
<command> -foutput.txt
-<command> -f output.txt
-<command> -f=output.txt
+
<command> -foutput.txt
+<command> -f output.txt
+<command> -f=output.txt
@@ -15450,12 +15175,12 @@

2

-
// valid (separator between --file and its parameter)
-<command> --file output.txt
-<command> --file=output.txt
+
// valid (separator between --file and its parameter)
+<command> --file output.txt
+<command> --file=output.txt
 
-// invalid (picocli will not recognize the --file option when attached to its parameter)
-<command> --fileoutput.txt
+// invalid (picocli will not recognize the --file option when attached to its parameter) +<command> --fileoutput.txt
@@ -15470,33 +15195,33 @@

21.
Java
-
@Command(separator = ":")  // declaratively set a separator
-class OptionArg {
-    @Option(names = { "-f", "--file" }) String file;
-}
+
@Command(separator = ":")  // declaratively set a separator
+class OptionArg {
+    @Option(names = { "-f", "--file" }) String file;
+}
Kotlin
-
@Command(separator = ":")  // declaratively set a separator
-class OptionArg {
-    @Option(names = ["-f", "--file"]) lateinit var file: String
-}
+
@Command(separator = ":")  // declaratively set a separator
+class OptionArg {
+    @Option(names = ["-f", "--file"]) lateinit var file: String
+}
Java
-
OptionArg optionArg = CommandLine.populateCommand(new OptionArg(), "-f:output.txt");
-assert optionArg.file.equals("output.txt");
+
OptionArg optionArg = CommandLine.populateCommand(new OptionArg(), "-f:output.txt");
+assert optionArg.file.equals("output.txt");
Kotlin
-
val optionArg = CommandLine.populateCommand(OptionArg(), "-f:output.txt")
-assertEquals("output.txt", optionArg.file)
+
val optionArg = CommandLine.populateCommand(OptionArg(), "-f:output.txt")
+assertEquals("output.txt", optionArg.file)
@@ -15506,23 +15231,23 @@

21.
Java
-
OptionArg optionArg     = new OptionArg();
-CommandLine commandLine = new CommandLine(optionArg);
+
OptionArg optionArg     = new OptionArg();
+CommandLine commandLine = new CommandLine(optionArg);
 
-commandLine.setSeparator(":"); // programmatically set a separator
-commandLine.parseArgs("-f:output.txt");
-assert optionArg.file.equals("output.txt");
+commandLine.setSeparator(":"); // programmatically set a separator +commandLine.parseArgs("-f:output.txt"); +assert optionArg.file.equals("output.txt");
Kotlin
-
val optionArg = OptionArg()
-val commandLine = CommandLine(optionArg)
+
val optionArg = OptionArg()
+val commandLine = CommandLine(optionArg)
 
-commandLine.separator = ":" // programmatically set a separator
-commandLine.parseArgs("-f:output.txt")
-assertEquals("output.txt", optionArg.file)
+commandLine.separator = ":" // programmatically set a separator +commandLine.parseArgs("-f:output.txt") +assertEquals("output.txt", optionArg.file)

@@ -15550,21 +15275,21 @@

Java 15
-
@Option(names = { "-v", "--verbose" },
-  description = """
+
@Option(names = { "-v", "--verbose" },
+  description = """
                 Verbose mode. Helpful for troubleshooting.
                 Multiple -v options increase the verbosity.
-                """) // write description in text block
+ """) // write description in text block
Kotlin
-
@Option(names = [ "-v", "--verbose" ],
-  description = ["""
+
@Option(names = [ "-v", "--verbose" ],
+  description = ["""
                  Verbose mode. Helpful for troubleshooting.
                  Multiple -v options increase the verbosity.
-                 """]) // write description in text block
+ """]) // write description in text block
@@ -15587,57 +15312,57 @@

22.1. Guice
Java
-
import com.google.inject.*;
-import picocli.CommandLine;
-import picocli.CommandLine.IFactory;
+
import com.google.inject.*;
+import picocli.CommandLine;
+import picocli.CommandLine.IFactory;
 
-public class GuiceFactory implements IFactory {
-    private final Injector injector = Guice.createInjector(new DemoModule());
+public class GuiceFactory implements IFactory {
+    private final Injector injector = Guice.createInjector(new DemoModule());
 
-    @Override
-    public <K> K create(Class<K> aClass) throws Exception {
-        try {
-            return injector.getInstance(aClass);
-        } catch (ConfigurationException ex) { // no implementation found in Guice configuration
-            return CommandLine.defaultFactory().create(aClass); // fallback if missing
-        }
-    }
+    @Override
+    public <K> K create(Class<K> aClass) throws Exception {
+        try {
+            return injector.getInstance(aClass);
+        } catch (ConfigurationException ex) { // no implementation found in Guice configuration
+            return CommandLine.defaultFactory().create(aClass); // fallback if missing
+        }
+    }
 
-    static class DemoModule extends AbstractModule {
-        @Override
-        protected void configure() {
-            bind(java.util.List.class).to(java.util.LinkedList.class);
-        }
-    }
-}
+ static class DemoModule extends AbstractModule { + @Override + protected void configure() { + bind(java.util.List.class).to(java.util.LinkedList.class); + } + } +}
Kotlin
-
import com.google.inject.*
-import picocli.CommandLine
-import picocli.CommandLine.IFactory
+
import com.google.inject.*
+import picocli.CommandLine
+import picocli.CommandLine.IFactory
 
-class GuiceFactory : IFactory {
-    private val injector = Guice.createInjector(DemoModule())
+class GuiceFactory : IFactory {
+    private val injector = Guice.createInjector(DemoModule())
 
-    @Throws(Exception::class)
-    override fun <K> create(aClass: Class<K>): K {
-        return try {
-            injector.getInstance(aClass)
-        } catch (ex: ConfigurationException) { // no implementation found in Guice configuration
-            CommandLine.defaultFactory().create(aClass) // fallback if missing
-        }
-    }
+    @Throws(Exception::class)
+    override fun <K> create(aClass: Class<K>): K {
+        return try {
+            injector.getInstance(aClass)
+        } catch (ex: ConfigurationException) { // no implementation found in Guice configuration
+            CommandLine.defaultFactory().create(aClass) // fallback if missing
+        }
+    }
 
-    class DemoModule : AbstractModule() {
-        override fun configure() {
-            bind(object : TypeLiteral<kotlin.collections.List<*>>() {})
-                .toInstance(kotlin.collections.ArrayList<Any>())
-        }
-    }
-}
+ class DemoModule : AbstractModule() { + override fun configure() { + bind(object : TypeLiteral<kotlin.collections.List<*>>() {}) + .toInstance(kotlin.collections.ArrayList<Any>()) + } + } +}
@@ -15646,48 +15371,48 @@

22.1. Guice
Java
-
import javax.inject.*;
-import picocli.CommandLine;
-import picocli.CommandLine.*;
+
import javax.inject.*;
+import picocli.CommandLine;
+import picocli.CommandLine.*;
 
-@Command(name = "di-demo")
-public class InjectionDemo implements Runnable {
-    @Inject java.util.List list;
+@Command(name = "di-demo")
+public class InjectionDemo implements Runnable {
+    @Inject java.util.List list;
 
-    @Option(names = "-x") int x;
+    @Option(names = "-x") int x;
 
-    public static void main(String[] args) {
-        new CommandLine(InjectionDemo.class, new GuiceFactory()).execute(args);
-    }
+    public static void main(String[] args) {
+        new CommandLine(InjectionDemo.class, new GuiceFactory()).execute(args);
+    }
 
-    @Override
-    public void run() {
-        assert list instanceof java.util.LinkedList;
-    }
-}
+ @Override + public void run() { + assert list instanceof java.util.LinkedList; + } +}
Kotlin
-
import picocli.CommandLine
-import picocli.CommandLine.Command
-import javax.inject.Inject
+
import picocli.CommandLine
+import picocli.CommandLine.Command
+import javax.inject.Inject
 
-@Command(name = "di-demo")
-class InjectionDemo : Runnable {
-    @Inject lateinit var list: kotlin.collections.List<Any>
+@Command(name = "di-demo")
+class InjectionDemo : Runnable {
+    @Inject lateinit var list: kotlin.collections.List<Any>
 
-    @CommandLine.Option(names = ["-x"]) var x = 0
+    @CommandLine.Option(names = ["-x"]) var x = 0
 
-    override fun run() {
-        assert(list is kotlin.collections.ArrayList<*>)
-    }
-}
+    override fun run() {
+        assert(list is kotlin.collections.ArrayList<*>)
+    }
+}
 
-fun main(args: Array<String>) {
-    CommandLine(InjectionDemo::class.java, GuiceFactory()).execute(*args)
-}
+fun main(args: Array<String>) { + CommandLine(InjectionDemo::class.java, GuiceFactory()).execute(*args) +}

@@ -15716,27 +15441,27 @@

Maven
-
<dependency>
-  <groupId>info.picocli</groupId>
-  <artifactId>picocli-spring-boot-starter</artifactId>
-  <version>4.6.2</version>
-</dependency>
+
<dependency>
+  <groupId>info.picocli</groupId>
+  <artifactId>picocli-spring-boot-starter</artifactId>
+  <version>4.6.3-SNAPSHOT</version>
+</dependency>

Gradle (Groovy)
-
dependencies {
-    implementation 'info.picocli:picocli-spring-boot-starter:4.6.2'
-}
+
dependencies {
+    implementation 'info.picocli:picocli-spring-boot-starter:4.6.3-SNAPSHOT'
+}
Gradle (Kotlin)
-
dependencies {
-    implementation("info.picocli:picocli-spring-boot-starter:4.6.2")
-}
+
dependencies {
+    implementation("info.picocli:picocli-spring-boot-starter:4.6.3-SNAPSHOT")
+}
@@ -15748,40 +15473,40 @@

Java
-
import org.springframework.boot.*;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import picocli.CommandLine;
-import picocli.CommandLine.IFactory;
+
import org.springframework.boot.*;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import picocli.CommandLine;
+import picocli.CommandLine.IFactory;
 
-@SpringBootApplication
-public class MySpringMailer implements CommandLineRunner, ExitCodeGenerator {
+@SpringBootApplication
+public class MySpringMailer implements CommandLineRunner, ExitCodeGenerator {
 
-    private IFactory factory;        (1)
-    private MailCommand mailCommand; (2)
-    private int exitCode;
+    private IFactory factory;        (1)
+    private MailCommand mailCommand; (2)
+    private int exitCode;
 
-    // constructor injection
-    MySpringMailer(IFactory factory, MailCommand mailCommand) {
-        this.factory = factory;
-        this.mailCommand = mailCommand;
-    }
+    // constructor injection
+    MySpringMailer(IFactory factory, MailCommand mailCommand) {
+        this.factory = factory;
+        this.mailCommand = mailCommand;
+    }
 
-    @Override
-    public void run(String... args) {
-        // let picocli parse command line args and run the business logic
-        exitCode = new CommandLine(mailCommand, factory).execute(args);
-    }
+    @Override
+    public void run(String... args) {
+        // let picocli parse command line args and run the business logic
+        exitCode = new CommandLine(mailCommand, factory).execute(args);
+    }
 
-    @Override
-    public int getExitCode() {
-        return exitCode;
-    }
+    @Override
+    public int getExitCode() {
+        return exitCode;
+    }
 
-    public static void main(String[] args) {
-        // let Spring instantiate and inject dependencies
-        System.exit(SpringApplication.exit(SpringApplication.run(MySpringMailer.class, args)));
-    }
-}
+ public static void main(String[] args) { + // let Spring instantiate and inject dependencies + System.exit(SpringApplication.exit(SpringApplication.run(MySpringMailer.class, args))); + } +}

@@ -15799,37 +15524,37 @@

Kotlin
-
import org.springframework.boot.*
-import org.springframework.boot.autoconfigure.SpringBootApplication
-import picocli.CommandLine
-import picocli.CommandLine.IFactory
+
import org.springframework.boot.*
+import org.springframework.boot.autoconfigure.SpringBootApplication
+import picocli.CommandLine
+import picocli.CommandLine.IFactory
 
-@SpringBootApplication
-class MySpringMailer : CommandLineRunner, ExitCodeGenerator {
+@SpringBootApplication
+class MySpringMailer : CommandLineRunner, ExitCodeGenerator {
 
-    private var factory: IFactory        (1)
-    private var mailCommand: MailCommand (2)
-    private var exitCode = 0
+    private var factory: IFactory        (1)
+    private var mailCommand: MailCommand (2)
+    private var exitCode = 0
 
-    // constructor injection
-    constructor(factory: IFactory, mailCommand: MailCommand) {
-        this.factory = factory          // auto-configured to inject PicocliSpringFactory
-        this.mailCommand = mailCommand  // your @picocli.CommandLine.Command-annotated class
-    }
+    // constructor injection
+    constructor(factory: IFactory, mailCommand: MailCommand) {
+        this.factory = factory          // auto-configured to inject PicocliSpringFactory
+        this.mailCommand = mailCommand  // your @picocli.CommandLine.Command-annotated class
+    }
 
-    override fun run(vararg args: String) {
-        // let picocli parse command line args and run the business logic
-        exitCode = CommandLine(mailCommand, factory).execute(*args)
-    }
+    override fun run(vararg args: String) {
+        // let picocli parse command line args and run the business logic
+        exitCode = CommandLine(mailCommand, factory).execute(*args)
+    }
 
-    override fun getExitCode(): Int {
-        return exitCode
-    }
-}
+    override fun getExitCode(): Int {
+        return exitCode
+    }
+}
 
-fun main(args: Array<String>) {
-    runApplication<MySpringMailer>(*args)
-}
+fun main(args: Array<String>) { + runApplication<MySpringMailer>(*args) +}

@@ -15847,32 +15572,32 @@

Java
-
import org.springframework.stereotype.Component;
-import org.springframework.beans.factory.annotation.Autowired;
-import picocli.CommandLine.*;
-import java.util.List;
-import java.util.concurrent.Callable;
+
import org.springframework.stereotype.Component;
+import org.springframework.beans.factory.annotation.Autowired;
+import picocli.CommandLine.*;
+import java.util.List;
+import java.util.concurrent.Callable;
 
-@Component (1)
-@Command(name = "mailCommand")
-public class MailCommand implements Callable<Integer> {
+@Component (1)
+@Command(name = "mailCommand")
+public class MailCommand implements Callable<Integer> {
 
-    @Autowired private IMailService mailService; (3)
+    @Autowired private IMailService mailService; (3)
 
-    @Option(names = "--to", description = "email(s) of recipient(s)", required = true)
-    List<String> to;
+    @Option(names = "--to", description = "email(s) of recipient(s)", required = true)
+    List<String> to;
 
-    @Option(names = "--subject", description = "Subject")
-    String subject;
+    @Option(names = "--subject", description = "Subject")
+    String subject;
 
-    @Parameters(description = "Message to be sent")
-    String[] body = {};
+    @Parameters(description = "Message to be sent")
+    String[] body = {};
 
-    public Integer call() throws Exception {
-        mailService.sendMessage(to, subject, String.join(" ", body)); (2)
-        return 0;
-    }
-}
+ public Integer call() throws Exception { + mailService.sendMessage(to, subject, String.join(" ", body)); (2) + return 0; + } +}

@@ -15894,32 +15619,32 @@

Kotlin
-
import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.stereotype.Component
-import picocli.CommandLine.*
-import java.util.concurrent.Callable
+
import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.stereotype.Component
+import picocli.CommandLine.*
+import java.util.concurrent.Callable
 
-@Component (1)
-@Command(name = "mailCommand")
-class MailCommand : Callable<Int> {
+@Component (1)
+@Command(name = "mailCommand")
+class MailCommand : Callable<Int> {
 
-    @Autowired private lateinit var mailService: IMailService (3)
+    @Autowired private lateinit var mailService: IMailService (3)
 
-    @Option(names = ["--to"], description = ["email(s) of recipient(s)"], required = true)
-    private lateinit var to: List<String>
+    @Option(names = ["--to"], description = ["email(s) of recipient(s)"], required = true)
+    private lateinit var to: List<String>
 
-    @Option(names = ["--subject"], description = ["Subject"])
-    private var subject: String = ""
+    @Option(names = ["--subject"], description = ["Subject"])
+    private var subject: String = ""
 
-    @Parameters(description = ["Message to be sent"])
-    var body = arrayOf<String>()
+    @Parameters(description = ["Message to be sent"])
+    var body = arrayOf<String>()
 
-    @Throws(Exception::class)
-    override fun call(): Int {
-        mailService.sendMessage(to, subject, java.lang.String.join(" ", *body)) (2)
-        return 0
-    }
-}
+ @Throws(Exception::class) + override fun call(): Int { + mailService.sendMessage(to, subject, java.lang.String.join(" ", *body)) (2) + return 0 + } +}

@@ -15941,17 +15666,17 @@

Java
-
public interface IMailService {
-    void sendMessage(List<String> to, String subject, String text);
-}
+
public interface IMailService {
+    void sendMessage(List<String> to, String subject, String text);
+}

Kotlin
-
interface IMailService {
-    fun sendMessage(to: List<String>, subject: String, text: String)
-}
+
interface IMailService {
+    fun sendMessage(to: List<String>, subject: String, text: String)
+}
@@ -15960,36 +15685,36 @@

Java
-
import org.slf4j.*;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.mail.*;
-import org.springframework.mail.javamail.JavaMailSender;
-import org.springframework.stereotype.Service;
-import java.util.List;
+
import org.slf4j.*;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.mail.*;
+import org.springframework.mail.javamail.JavaMailSender;
+import org.springframework.stereotype.Service;
+import java.util.List;
 
-@Service("MailService")
-public class MailServiceImpl implements IMailService {
+@Service("MailService")
+public class MailServiceImpl implements IMailService {
 
-    private static final Logger LOGGER= LoggerFactory.getLogger(MailServiceImpl.class);
-    private static final String NOREPLY_ADDRESS = "noreply@picocli.info";
+    private static final Logger LOGGER= LoggerFactory.getLogger(MailServiceImpl.class);
+    private static final String NOREPLY_ADDRESS = "noreply@picocli.info";
 
-    @Autowired private JavaMailSender emailSender; (1)
+    @Autowired private JavaMailSender emailSender; (1)
 
-    @Override
-    public void sendMessage(List<String> to, String subject, String text) {
-        try {
-            SimpleMailMessage message = new SimpleMailMessage(); // create message
-            message.setFrom(NOREPLY_ADDRESS);                    // compose message
-            for (String recipient : to) { message.setTo(recipient); }
-            message.setSubject(subject);
-            message.setText(text);
-            emailSender.send(message);                           // send message
+    @Override
+    public void sendMessage(List<String> to, String subject, String text) {
+        try {
+            SimpleMailMessage message = new SimpleMailMessage(); // create message
+            message.setFrom(NOREPLY_ADDRESS);                    // compose message
+            for (String recipient : to) { message.setTo(recipient); }
+            message.setSubject(subject);
+            message.setText(text);
+            emailSender.send(message);                           // send message
 
-            LOGGER.info("Mail to {} sent! Subject: {}, Body: {}", to, subject, text); (2)
-        }
-        catch (MailException e) { e.printStackTrace(); }
-    }
-}
+ LOGGER.info("Mail to {} sent! Subject: {}, Body: {}", to, subject, text); (2) + } + catch (MailException e) { e.printStackTrace(); } + } +}

@@ -16007,36 +15732,36 @@

Kotlin
-
import org.slf4j.LoggerFactory
-import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.mail.*
-import org.springframework.mail.javamail.JavaMailSender
-import org.springframework.stereotype.Service
-
-@Service("MailService")
-class MailServiceImpl : IMailService {
-
-    private val LOGGER = LoggerFactory.getLogger(MailServiceImpl::class.java)
-    private val NOREPLY_ADDRESS = "noreply@picocli.info"
-
-    @Autowired private lateinit var emailSender: JavaMailSender (1)
-
-    override fun sendMessage(to: List<String>, subject: String, text: String) {
-        try {
-            val message = SimpleMailMessage() // create message
-            message.setFrom(NOREPLY_ADDRESS)  // compose message
-            for (recipient in to) {
-                message.setTo(recipient)
-            }
-            message.setSubject(subject)
-            message.setText(text)
-            emailSender.send(message)        // send message
-            LOGGER.info("Mail to {} sent! Subject: {}, Body: {}", to, subject, text) (2)
-        } catch (e: MailException) {
-            e.printStackTrace()
-        }
-    }
-}
+
import org.slf4j.LoggerFactory
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.mail.*
+import org.springframework.mail.javamail.JavaMailSender
+import org.springframework.stereotype.Service
+
+@Service("MailService")
+class MailServiceImpl : IMailService {
+
+    private val LOGGER = LoggerFactory.getLogger(MailServiceImpl::class.java)
+    private val NOREPLY_ADDRESS = "noreply@picocli.info"
+
+    @Autowired private lateinit var emailSender: JavaMailSender (1)
+
+    override fun sendMessage(to: List<String>, subject: String, text: String) {
+        try {
+            val message = SimpleMailMessage() // create message
+            message.setFrom(NOREPLY_ADDRESS)  // compose message
+            for (recipient in to) {
+                message.setTo(recipient)
+            }
+            message.setSubject(subject)
+            message.setText(text)
+            emailSender.send(message)        // send message
+            LOGGER.info("Mail to {} sent! Subject: {}, Body: {}", to, subject, text) (2)
+        } catch (e: MailException) {
+            e.printStackTrace()
+        }
+    }
+}

@@ -16125,13 +15850,13 @@

Java
-
@Unmatched List<String> unmatched;
+
@Unmatched List<String> unmatched;

Kotlin
-
@Unmatched lateinit var unmatched: List<String>
+
@Unmatched lateinit var unmatched: List<String>
@@ -16159,7 +15884,7 @@

22.
-
mn create-cli-app git-stars --features http-client --lang=java
+
mn create-cli-app git-stars --features http-client --lang=java
 | Application created at /home/user/projects/micronaut/git-stars
@@ -16172,73 +15897,73 @@

22.
Java
-
import java.util.Map;
-import javax.inject.Inject;
-import picocli.CommandLine.Command;
-import picocli.CommandLine.Parameters;
-import io.micronaut.configuration.picocli.PicocliRunner;
-import io.micronaut.http.client.annotation.*;
-import io.micronaut.http.client.*;
+
import java.util.Map;
+import javax.inject.Inject;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Parameters;
+import io.micronaut.configuration.picocli.PicocliRunner;
+import io.micronaut.http.client.annotation.*;
+import io.micronaut.http.client.*;
 
-import static io.micronaut.http.HttpRequest.*;
+import static io.micronaut.http.HttpRequest.*;
 
-@Command(name = "git-stars", description = "Retrieve number of stars for a GitHub project",
-        mixinStandardHelpOptions = true)
-public class GitStarsCommand implements Runnable {
+@Command(name = "git-stars", description = "Retrieve number of stars for a GitHub project",
+        mixinStandardHelpOptions = true)
+public class GitStarsCommand implements Runnable {
 
-    @Client("https://api.github.com")
-    @Inject RxHttpClient client; // example injected service
+    @Client("https://api.github.com")
+    @Inject RxHttpClient client; // example injected service
 
-    @Parameters(description = "GitHub slug", paramLabel = "<owner/repo>",
-                defaultValue = "remkop/picocli")
-    String slug;
+    @Parameters(description = "GitHub slug", paramLabel = "<owner/repo>",
+                defaultValue = "remkop/picocli")
+    String slug;
 
-    public static void main(String[] args) {
-        PicocliRunner.execute(GitStarsCommand.class, args);
-    }
+    public static void main(String[] args) {
+        PicocliRunner.execute(GitStarsCommand.class, args);
+    }
 
-    public void run() {
-        Map m = client.retrieve(GET("/repos/" + slug).header(
-                "User-Agent", "remkop-picocli"), Map.class).blockingFirst();
-        System.out.printf("%s has %s stars%n", slug, m.get("stargazers_count"));
-    }
-}
+ public void run() { + Map m = client.retrieve(GET("/repos/" + slug).header( + "User-Agent", "remkop-picocli"), Map.class).blockingFirst(); + System.out.printf("%s has %s stars%n", slug, m.get("stargazers_count")); + } +}
Kotlin
-
import javax.inject.Inject
-import picocli.CommandLine.Command
-import picocli.CommandLine.Parameters
-import io.micronaut.configuration.picocli.PicocliRunner
-import io.micronaut.http.HttpRequest
-import io.micronaut.http.client.RxHttpClient
-
-@Command(name = "git-stars-kotlin", description = ["Retrieve star count for GitHub project"],
-         mixinStandardHelpOptions = true)
-class GitStarsKotlinCommand : Runnable {
-
-    val URI_GitHub_API: String = "https://api.github.com"
-    @Inject lateinit var client: RxHttpClient // example injected service
-
-    @Parameters(description = ["GitHub slug"], paramLabel = "<owner/repo>",
-        defaultValue = "remkop/picocli")
-    lateinit var slug: String
-
-    override fun run() {
-        val req = HttpRequest.GET<Any>("${URI_GitHub_API}/repos/$slug")
-        req.header("User-Agent", "remkop-picocli")
-        val flowable = client.retrieve(req, MutableMap::class.java).blockingFirst()
-        println("$slug has ${flowable.get("stargazers_count")} stars")
-    }
+
import javax.inject.Inject
+import picocli.CommandLine.Command
+import picocli.CommandLine.Parameters
+import io.micronaut.configuration.picocli.PicocliRunner
+import io.micronaut.http.HttpRequest
+import io.micronaut.http.client.RxHttpClient
+
+@Command(name = "git-stars-kotlin", description = ["Retrieve star count for GitHub project"],
+         mixinStandardHelpOptions = true)
+class GitStarsKotlinCommand : Runnable {
+
+    val URI_GitHub_API: String = "https://api.github.com"
+    @Inject lateinit var client: RxHttpClient // example injected service
+
+    @Parameters(description = ["GitHub slug"], paramLabel = "<owner/repo>",
+        defaultValue = "remkop/picocli")
+    lateinit var slug: String
+
+    override fun run() {
+        val req = HttpRequest.GET<Any>("${URI_GitHub_API}/repos/$slug")
+        req.header("User-Agent", "remkop-picocli")
+        val flowable = client.retrieve(req, MutableMap::class.java).blockingFirst()
+        println("$slug has ${flowable.get("stargazers_count")} stars")
+    }
 
-    companion object {
-        @JvmStatic fun main(args: Array<String>) {
-            PicocliRunner.execute(GitStarsKotlinCommand::class.java, *args)
-        }
-    }
-}
+ companion object { + @JvmStatic fun main(args: Array<String>) { + PicocliRunner.execute(GitStarsKotlinCommand::class.java, *args) + } + } +}
@@ -16246,11 +15971,11 @@

22.

-
cd git-stars
-./gradlew run --args="micronaut-projects/micronaut-core"
-# ...
-> Task :run
-21:12:17.660 [main] INFO  i.m.context.env.DefaultEnvironment - Established active environments: [cli]
+
cd git-stars
+./gradlew run --args="micronaut-projects/micronaut-core"
+# ...
+> Task :run
+21:12:17.660 [main] INFO  i.m.context.env.DefaultEnvironment - Established active environments: [cli]
 micronaut-projects/micronaut-core has 4245 stars
@@ -16260,8 +15985,8 @@

22.
mn create-command second
-Rendered command to src/main/java/git/stars/SecondCommand.java
-Rendered command test to src/test/java/git/stars/SecondCommandTest.java
+Rendered command to src/main/java/git/stars/SecondCommand.java +Rendered command test to src/test/java/git/stars/SecondCommandTest.java
@@ -16269,9 +15994,9 @@

22.

-
mn test --tests git.stars.SecondCommandTest
-# ...
-> :test > Executing test git.stars.SecondCommandTest
+
mn test --tests git.stars.SecondCommandTest
+# ...
+> :test > Executing test git.stars.SecondCommandTest
@@ -16303,56 +16028,56 @@

22.4. Q
Java
-
import javax.inject.Inject;
-import java.util.*;
-import io.quarkus.mailer.*;
-import io.quarkus.picocli.runtime.annotations.TopCommand;
-import picocli.CommandLine.*;
-
-@TopCommand (3)
-@Command (subcommands = MailCommand.HeaderCommand.class, requiredOptionMarker = '*')
-public class MailCommand implements Runnable { (1)
-    private Mail mail = new Mail();
-    @Inject Mailer mailer;  // Quarkus mailer
-
-    @Option(names = "--from", description = "email address of sender", required = true)
-    String from;
-
-    @Option(names = "--to", description = "email(s) of recipient(s)", required = true)
-    List<String> to;
-
-    @Option(names = "--subject", description = "Subject")
-    String subject;
-
-    @Parameters(description = "Message to be sent")
-    String[] body = {};
-
-    @Override
-    public void run() {
-        mail.setFrom(from)   // compose mail
-            .setTo(to)
-            .setSubject(subject)
-            .setText(String.join(" ", body));
-       mailer.send(mail);    // send mail
-    }
-
-    @Command(name = "headers", description = "adding custom header line(s)")
-    static class HeaderCommand implements Runnable { (2)
-        private static Map<String, List<String>> headerMap = new HashMap<>();
-        @ParentCommand private MailCommand parent;
-
-        @Option(names = "--header", paramLabel = "KEY=VALUE")
-        public void setProperty(Map<String, String> headers) {
-            headers.forEach((k,v) -> headerMap.put(k, Arrays.asList(v.split(" "))));
-        }
-
-        @Override
-        public void run() {
-            parent.mail.setHeaders(headerMap);
-            parent.run();
-        }
-    }
-}
+
import javax.inject.Inject;
+import java.util.*;
+import io.quarkus.mailer.*;
+import io.quarkus.picocli.runtime.annotations.TopCommand;
+import picocli.CommandLine.*;
+
+@TopCommand (3)
+@Command (subcommands = MailCommand.HeaderCommand.class, requiredOptionMarker = '*')
+public class MailCommand implements Runnable { (1)
+    private Mail mail = new Mail();
+    @Inject Mailer mailer;  // Quarkus mailer
+
+    @Option(names = "--from", description = "email address of sender", required = true)
+    String from;
+
+    @Option(names = "--to", description = "email(s) of recipient(s)", required = true)
+    List<String> to;
+
+    @Option(names = "--subject", description = "Subject")
+    String subject;
+
+    @Parameters(description = "Message to be sent")
+    String[] body = {};
+
+    @Override
+    public void run() {
+        mail.setFrom(from)   // compose mail
+            .setTo(to)
+            .setSubject(subject)
+            .setText(String.join(" ", body));
+       mailer.send(mail);    // send mail
+    }
+
+    @Command(name = "headers", description = "adding custom header line(s)")
+    static class HeaderCommand implements Runnable { (2)
+        private static Map<String, List<String>> headerMap = new HashMap<>();
+        @ParentCommand private MailCommand parent;
+
+        @Option(names = "--header", paramLabel = "KEY=VALUE")
+        public void setProperty(Map<String, String> headers) {
+            headers.forEach((k,v) -> headerMap.put(k, Arrays.asList(v.split(" "))));
+        }
+
+        @Override
+        public void run() {
+            parent.mail.setHeaders(headerMap);
+            parent.run();
+        }
+    }
+}
@@ -16374,55 +16099,55 @@

22.4. Q
Kotlin
-
import io.quarkus.mailer.*
-import io.quarkus.picocli.runtime.annotations.TopCommand
-import picocli.CommandLine.*
-import javax.inject.Inject
-import kotlin.collections.HashMap
-
-@TopCommand (3)
-@Command(subcommands = [MailCommand.HeaderCommand::class], requiredOptionMarker = '*')
-class MailCommand : Runnable { (1)
-    private val mail = Mail()
-    @Inject private lateinit var mailer : Mailer   // Quarkus mailer
-
-    @Option(names = ["--from"], description = ["email address of sender"], required = true)
-    private lateinit var from: String
-
-    @Option(names = ["--to"], description = ["email(s) of recipient(s)"], required = true)
-    private lateinit var to: List<String>
-
-    @Option(names = ["--subject"], description = ["Subject"])
-    private var subject: String? = null
-
-    @Parameters(description = ["Message to be sent"])
-    private var body = arrayOf<String>()
-
-    override fun run() {
-        mail.setFrom(from) // compose mail
-            .setTo(to)
-            .setSubject(subject)
-            .text = body.joinToString(separator = " ")
-        mailer.send(mail) // send mail
-    }
-
-    @Command(name = "headers", description = ["adding custom header line(s)"])
-    internal class HeaderCommand : Runnable { (2)
-        private val headerMap: MutableMap<String, List<String>> = HashMap()
-        @ParentCommand private lateinit var parent: MailCommand
-
-        @Option(names = ["--header"], paramLabel = "KEY=VALUE")
-        fun setProperty(headers: Map<String, String>) {
-            headers.forEach { (k: String, v: String) ->
-                headerMap[k] = listOf(*v.split(" ").toTypedArray()) }
-        }
-
-        override fun run() {
-            parent.mail.headers = headerMap
-            parent.run()
-        }
-    }
-}
+
import io.quarkus.mailer.*
+import io.quarkus.picocli.runtime.annotations.TopCommand
+import picocli.CommandLine.*
+import javax.inject.Inject
+import kotlin.collections.HashMap
+
+@TopCommand (3)
+@Command(subcommands = [MailCommand.HeaderCommand::class], requiredOptionMarker = '*')
+class MailCommand : Runnable { (1)
+    private val mail = Mail()
+    @Inject private lateinit var mailer : Mailer   // Quarkus mailer
+
+    @Option(names = ["--from"], description = ["email address of sender"], required = true)
+    private lateinit var from: String
+
+    @Option(names = ["--to"], description = ["email(s) of recipient(s)"], required = true)
+    private lateinit var to: List<String>
+
+    @Option(names = ["--subject"], description = ["Subject"])
+    private var subject: String? = null
+
+    @Parameters(description = ["Message to be sent"])
+    private var body = arrayOf<String>()
+
+    override fun run() {
+        mail.setFrom(from) // compose mail
+            .setTo(to)
+            .setSubject(subject)
+            .text = body.joinToString(separator = " ")
+        mailer.send(mail) // send mail
+    }
+
+    @Command(name = "headers", description = ["adding custom header line(s)"])
+    internal class HeaderCommand : Runnable { (2)
+        private val headerMap: MutableMap<String, List<String>> = HashMap()
+        @ParentCommand private lateinit var parent: MailCommand
+
+        @Option(names = ["--header"], paramLabel = "KEY=VALUE")
+        fun setProperty(headers: Map<String, String>) {
+            headers.forEach { (k: String, v: String) ->
+                headerMap[k] = listOf(*v.split(" ").toTypedArray()) }
+        }
+
+        override fun run() {
+            parent.mail.headers = headerMap
+            parent.run()
+        }
+    }
+}
@@ -16545,32 +16270,32 @@

22.5. C

-
import javax.enterprise.context.ApplicationScoped;
-import javax.enterprise.inject.Instance;
-import javax.enterprise.inject.spi.CDI;
+
import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.inject.Instance;
+import javax.enterprise.inject.spi.CDI;
 
-import picocli.CommandLine;
-import picocli.CommandLine.IFactory;
+import picocli.CommandLine;
+import picocli.CommandLine.IFactory;
 
-/**
+/**
  * Factory used by picocli to look up subcommands and other classes
  * in the CDI container before instantiating them directly,
  * to support dependency injection in subcommands and other classes.
- */
-@ApplicationScoped
-public class CDIFactory implements IFactory {
+ */
+@ApplicationScoped
+public class CDIFactory implements IFactory {
 
-    private final IFactory fallbackFactory = CommandLine.defaultFactory();
+    private final IFactory fallbackFactory = CommandLine.defaultFactory();
 
-    @Override
-    public <K> K create(Class<K> cls) throws Exception {
-        Instance<K> instance = CDI.current().select(cls);
-        if (instance.isResolvable()) {
-            return instance.get();
-        }
-        return defaultFactory.create(cls);
-    }
-}
+ @Override + public <K> K create(Class<K> cls) throws Exception { + Instance<K> instance = CDI.current().select(cls); + if (instance.isResolvable()) { + return instance.get(); + } + return defaultFactory.create(cls); + } +}
@@ -16578,22 +16303,22 @@

22.5. C

-
@Command(name = "cdi-app", mixinStandardHelpOptions = true)
-class MyCDIApp implements Runnable {
+
@Command(name = "cdi-app", mixinStandardHelpOptions = true)
+class MyCDIApp implements Runnable {
 
-    @Option(names = {"-x", "--option"}, description = "example option")
-    boolean flag;
+    @Option(names = {"-x", "--option"}, description = "example option")
+    boolean flag;
 
-    @Override
-    public void run() {
-        // business logic
-    }
+    @Override
+    public void run() {
+        // business logic
+    }
 
-    public static void main(String[] args) {
-        CDIFactory cdiFactory = CDI.current().select(CDIFactory.class).get();
-        new CommandLine(MyCDIApp.class, cdiFactory).execute(args);
-    }
-}
+ public static void main(String[] args) { + CDIFactory cdiFactory = CDI.current().select(CDIFactory.class).get(); + new CommandLine(MyCDIApp.class, cdiFactory).execute(args); + } +}

@@ -16703,14 +16428,14 @@

25. Tracing

-
# create a custom 'git' command that invokes picocli.Demo$Git with tracing switched on
-alias git='java -Dpicocli.trace -cp picocli-all.jar picocli.Demo$Git'
+
# create a custom 'git' command that invokes picocli.Demo$Git with tracing switched on
+alias git='java -Dpicocli.trace -cp picocli-all.jar picocli.Demo$Git'
 
-# invoke our command with some parameters
-git --git-dir=/home/rpopma/picocli commit -m "Fixed typos" -- src1.java src2.java src3.java
+# invoke our command with some parameters
+git --git-dir=/home/rpopma/picocli commit -m "Fixed typos" -- src1.java src2.java src3.java
 
-# remove our 'git' pseudonym from the current shell environment
-unalias git
+# remove our 'git' pseudonym from the current shell environment +unalias git
Kotlin
-
val app = MyApp()
-val cmd = CommandLine(app)
+
val app = MyApp()
+val cmd = CommandLine(app)
 
-val sw = StringWriter()
-cmd.out = PrintWriter(sw)
+val sw = StringWriter()
+cmd.out = PrintWriter(sw)
 
-// black box testing
-val exitCode = cmd.execute("-x", "-y=123")
-assertEquals(0, exitCode)
-assertEquals("Your output is abc...", sw.toString())
+// black box testing
+val exitCode = cmd.execute("-x", "-y=123")
+assertEquals(0, exitCode)
+assertEquals("Your output is abc...", sw.toString())
 
-// white box testing
-assertEquals("expectedValue1", app.state1)
-assertEquals("expectedValue2", app.state2)
+// white box testing +assertEquals("expectedValue1", app.state1) +assertEquals("expectedValue2", app.state2)
Kotlin
-
@Command
-class MyApp : Runnable {
-    @Spec lateinit var spec: CommandSpec
+
@Command
+class MyApp : Runnable {
+    @Spec lateinit var spec: CommandSpec
 
-    override fun run() {
-        // make testing easier by printing to the Err and Out streams provided by picocli
-        spec.commandLine().out.println("Your output is abc...")
-    }
-}
+ override fun run() { + // make testing easier by printing to the Err and Out streams provided by picocli + spec.commandLine().out.println("Your output is abc...") + } +}
@@ -16894,24 +16619,24 @@

-
import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemErr;
-import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemOutNormalized;
-// ...
+
import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemErr;
+import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemOutNormalized;
+// ...
 
-class MyTest {
-    @Test
-    void testMyApp() throws Exception {
-        String errText = tapSystemErr(() -> {
-            String outText = tapSystemOutNormalized(() -> {
-                new CommandLine(new MyApp()).execute("--option=value", "arg0", "arg1");
-            });
-            assertEquals("--option='value'\n" +
-                         "position[0]='arg0'\n" +
-                         "position[1]='arg1'\n", outText);
-        });
-        assertEquals("", errText);
-    }
-}
+class MyTest { + @Test + void testMyApp() throws Exception { + String errText = tapSystemErr(() -> { + String outText = tapSystemOutNormalized(() -> { + new CommandLine(new MyApp()).execute("--option=value", "arg0", "arg1"); + }); + assertEquals("--option='value'\n" + + "position[0]='arg0'\n" + + "position[1]='arg1'\n", outText); + }); + assertEquals("", errText); + } +}
@@ -16925,27 +16650,27 @@

-
import org.junit.contrib.java.lang.system.SystemErrRule;
-import org.junit.contrib.java.lang.system.SystemOutRule;
-// ...
-
-class MyTest {
-    @Rule
-    SystemErrRule systemErrRule = new SystemErrRule().enableLog().muteForSuccessfulTests();
-
-    @Rule
-    SystemOutRule systemOutRule = new SystemOutRule().enableLog().muteForSuccessfulTests();
-
-    @Test
-    void testMyApp() throws Exception {
-        new CommandLine(new MyApp()).execute("--option=value", "arg0", "arg1");
-        String expected = String.format("--option='value'%n" +
-                                        "position[0]='arg0'%n" +
-                                        "position[1]='arg1'%n");
-        assertEquals(expected, systemOutRule.getLog());
-        assertEquals("", systemErrRule.getLog());
-    }
-}
+
import org.junit.contrib.java.lang.system.SystemErrRule;
+import org.junit.contrib.java.lang.system.SystemOutRule;
+// ...
+
+class MyTest {
+    @Rule
+    SystemErrRule systemErrRule = new SystemErrRule().enableLog().muteForSuccessfulTests();
+
+    @Rule
+    SystemOutRule systemOutRule = new SystemOutRule().enableLog().muteForSuccessfulTests();
+
+    @Test
+    void testMyApp() throws Exception {
+        new CommandLine(new MyApp()).execute("--option=value", "arg0", "arg1");
+        String expected = String.format("--option='value'%n" +
+                                        "position[0]='arg0'%n" +
+                                        "position[1]='arg1'%n");
+        assertEquals(expected, systemOutRule.getLog());
+        assertEquals("", systemErrRule.getLog());
+    }
+}
@@ -16959,21 +16684,21 @@

<
-
ByteArrayOutputStream err = new ByteArrayOutputStream();
-ByteArrayOutputStream out = new ByteArrayOutputStream();
-PrintStream oldErr = System.err;
-PrintStream oldOut = System.out;
-try {
-    System.setErr(new PrintStream(err));           // setup
-    System.setOut(new PrintStream(out));
-    String[] args = "my command args".split(" ");  // test
-    new CommandLine(new MyApp()).execute(args);
-} finally {
-    System.setErr(oldErr);                         // teardown
-    System.setOut(oldOut);
-}
-assertEquals("MY COMMAND OUTPUT", out.toString()); // verify
-assertEquals("", err.toString());
+
ByteArrayOutputStream err = new ByteArrayOutputStream();
+ByteArrayOutputStream out = new ByteArrayOutputStream();
+PrintStream oldErr = System.err;
+PrintStream oldOut = System.out;
+try {
+    System.setErr(new PrintStream(err));           // setup
+    System.setOut(new PrintStream(out));
+    String[] args = "my command args".split(" ");  // test
+    new CommandLine(new MyApp()).execute(args);
+} finally {
+    System.setErr(oldErr);                         // teardown
+    System.setOut(oldOut);
+}
+assertEquals("MY COMMAND OUTPUT", out.toString()); // verify
+assertEquals("", err.toString());
-
//import org.junit.After;  // JUnit 4
-//import org.junit.Before; // JUnit 4
-import org.junit.jupiter.api.AfterEach;  // JUnit 5
-import org.junit.jupiter.api.BeforeEach; // JUnit 5
-//...
-class TestOutput {
-    final PrintStream originalOut = System.out;
-    final PrintStream originalErr = System.err;
-    final ByteArrayOutputStream out = new ByteArrayOutputStream();
-    final ByteArrayOutputStream err = new ByteArrayOutputStream();
-
-    //@Before   // JUnit 4
-    @BeforeEach // JUnit 5
-    public void setUpStreams() {
-        out.reset();
-        err.reset();
-        System.setOut(new PrintStream(out));
-        System.setErr(new PrintStream(err));
-    }
-
-    //@After   // JUnit 4
-    @AfterEach // JUnit 5
-    public void restoreStreams() {
-        System.setOut(originalOut);
-        System.setErr(originalErr);
-    }
-
-    @Test
-    public void test() {
-        String[] args = "my command args".split(" ");
-        new CommandLine(new MyApp()).execute(args);
-        assertEquals("MY COMMAND OUTPUT", out.toString());
-        assertEquals("", err.toString());
-    }
-}
+
//import org.junit.After;  // JUnit 4
+//import org.junit.Before; // JUnit 4
+import org.junit.jupiter.api.AfterEach;  // JUnit 5
+import org.junit.jupiter.api.BeforeEach; // JUnit 5
+//...
+class TestOutput {
+    final PrintStream originalOut = System.out;
+    final PrintStream originalErr = System.err;
+    final ByteArrayOutputStream out = new ByteArrayOutputStream();
+    final ByteArrayOutputStream err = new ByteArrayOutputStream();
+
+    //@Before   // JUnit 4
+    @BeforeEach // JUnit 5
+    public void setUpStreams() {
+        out.reset();
+        err.reset();
+        System.setOut(new PrintStream(out));
+        System.setErr(new PrintStream(err));
+    }
+
+    //@After   // JUnit 4
+    @AfterEach // JUnit 5
+    public void restoreStreams() {
+        System.setOut(originalOut);
+        System.setErr(originalErr);
+    }
+
+    @Test
+    public void test() {
+        String[] args = "my command args".split(" ");
+        new CommandLine(new MyApp()).execute(args);
+        assertEquals("MY COMMAND OUTPUT", out.toString());
+        assertEquals("", err.toString());
+    }
+}
@@ -17053,118 +16778,118 @@

Java 8
-
import static com.github.stefanbirkner.systemlambda.SystemLambda.catchSystemExit;
-// ...
-
-class MyTest {
-    @Command
-    static class MyApp implements Callable<Integer> {
-        public Integer call() {
-            System.out.println("Hi");
-            return 42;
-        }
-        public static void main(String[] args) {
-            System.exit(new CommandLine(new MyApp()).execute(args));
-        }
-    }
-
-    @Test
-    void testMyAppExit() throws Exception {
-        int exitCode = catchSystemExit(() -> {
-            MyApp.main();
-        });
-        assertEquals(42, exitCode);
-    }
-}
+
import static com.github.stefanbirkner.systemlambda.SystemLambda.catchSystemExit;
+// ...
+
+class MyTest {
+    @Command
+    static class MyApp implements Callable<Integer> {
+        public Integer call() {
+            System.out.println("Hi");
+            return 42;
+        }
+        public static void main(String[] args) {
+            System.exit(new CommandLine(new MyApp()).execute(args));
+        }
+    }
+
+    @Test
+    void testMyAppExit() throws Exception {
+        int exitCode = catchSystemExit(() -> {
+            MyApp.main();
+        });
+        assertEquals(42, exitCode);
+    }
+}
Java/Junit 5
-
import com.ginsberg.junit.exit.ExpectSystemExitWithStatus;
-import org.junit.jupiter.api.Test;
-// ...
-
-class MyTest {
-    @Command
-    static class MyApp implements Callable<Integer> {
-        @Override
-        public Integer call() throws Exception {
-            System.out.println("Hi");
-            return 42;
-        }
-        public static void main (String[] args) {
-            System.exit(new CommandLine(new MyApp()).execute(args));
-        }
-    }
-
-    @Test
-    @ExpectSystemExitWithStatus(42)
-    void testMyAppExit() {
-        MyApp.main(new String[] {});
-    }
-}
+
import com.ginsberg.junit.exit.ExpectSystemExitWithStatus;
+import org.junit.jupiter.api.Test;
+// ...
+
+class MyTest {
+    @Command
+    static class MyApp implements Callable<Integer> {
+        @Override
+        public Integer call() throws Exception {
+            System.out.println("Hi");
+            return 42;
+        }
+        public static void main (String[] args) {
+            System.exit(new CommandLine(new MyApp()).execute(args));
+        }
+    }
+
+    @Test
+    @ExpectSystemExitWithStatus(42)
+    void testMyAppExit() {
+        MyApp.main(new String[] {});
+    }
+}
Java/Junit 4
-
import org.junit.Rule;
-import org.junit.Test;
-import org.junit.contrib.java.lang.system.ExpectedSystemExit;
+
import org.junit.Rule;
+import org.junit.Test;
+import org.junit.contrib.java.lang.system.ExpectedSystemExit;
 
-class MyTest {
-    @Rule public final ExpectedSystemExit exit = ExpectedSystemExit.none();
+class MyTest {
+    @Rule public final ExpectedSystemExit exit = ExpectedSystemExit.none();
 
-    @Command
-    static class MyApp implements Callable<Integer> {
-        public Integer call() {
-            System.out.println("Hi");
-            return 42;
-        }
-        public static void main(String[] args) {
-            System.exit(new CommandLine(new MyApp()).execute(args));
-        }
-    }
+    @Command
+    static class MyApp implements Callable<Integer> {
+        public Integer call() {
+            System.out.println("Hi");
+            return 42;
+        }
+        public static void main(String[] args) {
+            System.exit(new CommandLine(new MyApp()).execute(args));
+        }
+    }
 
-    @Test
-    public void testExitCode() {
-        exit.expectSystemExitWithStatus(42);
-        MyApp.main();
-    }
-}
+ @Test + public void testExitCode() { + exit.expectSystemExitWithStatus(42); + MyApp.main(); + } +}
Kotlin/Kotest
-
import io.kotest.assertions.throwables.shouldThrow
-import io.kotest.core.spec.style.StringSpec
-import io.kotest.extensions.system.*
-import io.kotest.matchers.shouldBe
-// ...
+
import io.kotest.assertions.throwables.shouldThrow
+import io.kotest.core.spec.style.StringSpec
+import io.kotest.extensions.system.*
+import io.kotest.matchers.shouldBe
+// ...
 
-class SystemExitTest : StringSpec() {
+class SystemExitTest : StringSpec() {
 
-    override fun listeners() = listOf(SpecSystemExitListener)
+    override fun listeners() = listOf(SpecSystemExitListener)
 
-    init {
-        "Picocli app should exit process with return code 42" {
-            shouldThrow<SystemExitException> {
-                main(arrayOf())
-            }.exitCode shouldBe 42
-        }
-    }
-}
+    init {
+        "Picocli app should exit process with return code 42" {
+            shouldThrow<SystemExitException> {
+                main(arrayOf())
+            }.exitCode shouldBe 42
+        }
+    }
+}
 
-@Command
-class PicocliApp : Callable<Int> {
-    override fun call(): Int {
-        return 42
-    }
-}
+@Command
+class PicocliApp : Callable<Int> {
+    override fun call(): Int {
+        return 42
+    }
+}
 
-fun main(args: Array<String>) : Unit = exitProcess(CommandLine(PicocliApp()).execute(*args))
+fun main(args: Array<String>) : Unit = exitProcess(CommandLine(PicocliApp()).execute(*args))
@@ -17193,87 +16918,87 @@

Java 8
-
import static com.github.stefanbirkner.systemlambda.SystemLambda.withEnvironmentVariable;
-// ...
+
import static com.github.stefanbirkner.systemlambda.SystemLambda.withEnvironmentVariable;
+// ...
 
-@Test
-void testEnvVar() throws Exception {
-    class MyApp {
-        @Option(names = "--option", defaultValue = "${env:MYVAR}",
-                description = "Some option. Default: ${DEFAULT-VALUE}")
-        String option;
-    }
-    String actual = withEnvironmentVariable("MYVAR", "some-value")
-            .and("OTHER_VAR", "second value")
-            .execute(() -> new CommandLine(new MyApp())
-                            .getUsageMessage(CommandLine.Help.Ansi.OFF));
-
-    String expected = String.format("" +
-            "Usage: <main class> [--option=<option>]%n" +
-            "      --option=<option>   Some option. Default: some-value%n");
-    assertEquals(expected, actual);
-}
+@Test +void testEnvVar() throws Exception { + class MyApp { + @Option(names = "--option", defaultValue = "${env:MYVAR}", + description = "Some option. Default: ${DEFAULT-VALUE}") + String option; + } + String actual = withEnvironmentVariable("MYVAR", "some-value") + .and("OTHER_VAR", "second value") + .execute(() -> new CommandLine(new MyApp()) + .getUsageMessage(CommandLine.Help.Ansi.OFF)); + + String expected = String.format("" + + "Usage: <main class> [--option=<option>]%n" + + " --option=<option> Some option. Default: some-value%n"); + assertEquals(expected, actual); +}
Java/JUnit 4
-
import org.junit.contrib.java.lang.system.EnvironmentVariables;
-// ...
+
import org.junit.contrib.java.lang.system.EnvironmentVariables;
+// ...
 
-class MyTest {
-    @Rule
-    public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
+class MyTest {
+    @Rule
+    public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
 
-    @Test
-    public void testEnvVar() {
-        class MyApp {
-            @Option(names = "--option", defaultValue = "${env:MYVAR}",
-                    description = "Some option. Default: ${DEFAULT-VALUE}")
-            String option;
-        }
-        environmentVariables.clear("MYVAR", "OTHER_VAR", "THIRD_VAR");
-        environmentVariables.set("MYVAR", "some-value");
-        environmentVariables.set("OTHER_VAR", "second value");
+    @Test
+    public void testEnvVar() {
+        class MyApp {
+            @Option(names = "--option", defaultValue = "${env:MYVAR}",
+                    description = "Some option. Default: ${DEFAULT-VALUE}")
+            String option;
+        }
+        environmentVariables.clear("MYVAR", "OTHER_VAR", "THIRD_VAR");
+        environmentVariables.set("MYVAR", "some-value");
+        environmentVariables.set("OTHER_VAR", "second value");
 
-        String actual = new CommandLine(new MyApp())
-                .getUsageMessage(CommandLine.Help.Ansi.OFF);
+        String actual = new CommandLine(new MyApp())
+                .getUsageMessage(CommandLine.Help.Ansi.OFF);
 
-        String expected = String.format("" +
-                "Usage: <main class> [--option=<option>]%n" +
-                "      --option=<option>   Some option. Default: some-value%n");
-        assertEquals(expected, actual);
-    }
-}
+ String expected = String.format("" + + "Usage: <main class> [--option=<option>]%n" + + " --option=<option> Some option. Default: some-value%n"); + assertEquals(expected, actual); + } +}
Kotlin/Kotest
-
import io.kotest.core.spec.style.StringSpec
-import io.kotest.extensions.system.withEnvironment
-import io.kotest.matchers.shouldBe
-import picocli.CommandLine
-import picocli.CommandLine.Command
-
-class EnvironmentVarTest : StringSpec() {
-    init {
-        "env var" {
-            withEnvironment(mapOf("MYVAR" to "some-value", "OTHER_VAR" to "second value")) {
-                CommandLine(MyApp()).getUsageMessage(CommandLine.Help.Ansi.OFF) shouldBe
-                "Usage: <main class> [--option=<option>]" + System.lineSeparator() +
-                "      --option=<option>   Some option. Default: some-value" + System.lineSeparator()
-            }
-        }
-    }
-}
-
-@Command
-class MyApp {
-    @CommandLine.Option(names = ["--option"], defaultValue = "\${env:MYVAR}",
-        description = ["Some option. Default: \${DEFAULT-VALUE}"])
-    lateinit var option: String
-}
+
import io.kotest.core.spec.style.StringSpec
+import io.kotest.extensions.system.withEnvironment
+import io.kotest.matchers.shouldBe
+import picocli.CommandLine
+import picocli.CommandLine.Command
+
+class EnvironmentVarTest : StringSpec() {
+    init {
+        "env var" {
+            withEnvironment(mapOf("MYVAR" to "some-value", "OTHER_VAR" to "second value")) {
+                CommandLine(MyApp()).getUsageMessage(CommandLine.Help.Ansi.OFF) shouldBe
+                "Usage: <main class> [--option=<option>]" + System.lineSeparator() +
+                "      --option=<option>   Some option. Default: some-value" + System.lineSeparator()
+            }
+        }
+    }
+}
+
+@Command
+class MyApp {
+    @CommandLine.Option(names = ["--option"], defaultValue = "\${env:MYVAR}",
+        description = ["Some option. Default: \${DEFAULT-VALUE}"])
+    lateinit var option: String
+}
-
alias mycommand='java -cp "/path/to/picocli-4.6.2.jar:/path/to/myapp.jar" org.myorg.MainClass'
+
alias mycommand='java -cp "/path/to/picocli-4.6.3-SNAPSHOT.jar:/path/to/myapp.jar" org.myorg.MainClass'
@@ -17624,25 +17349,25 @@

30.1.2. G
-
@Grab('info.picocli:picocli-groovy:4.6.2')
-@GrabConfig(systemClassLoader=true)
-@Command(name = "myScript",
-        mixinStandardHelpOptions = true, // add --help and --version options
-        description = "@|bold Groovy script|@ @|underline picocli|@ example")
-@picocli.groovy.PicocliScript2
-import groovy.transform.Field
-import static picocli.CommandLine.*
+
@Grab('info.picocli:picocli-groovy:4.6.3-SNAPSHOT')
+@GrabConfig(systemClassLoader=true)
+@Command(name = "myScript",
+        mixinStandardHelpOptions = true, // add --help and --version options
+        description = "@|bold Groovy script|@ @|underline picocli|@ example")
+@picocli.groovy.PicocliScript2
+import groovy.transform.Field
+import static picocli.CommandLine.*
 
-@Option(names = ["-c", "--count"], description = "number of repetitions")
-@Field int count = 1;
+@Option(names = ["-c", "--count"], description = "number of repetitions")
+@Field int count = 1;
 
-// PicocliBaseScript2 prints usage help or version if requested by the user
+// PicocliBaseScript2 prints usage help or version if requested by the user
 
-count.times {
-   println "hi"
-}
-// the CommandLine that parsed the args is available as a property
-assert this.commandLine.commandName == "myScript"
+count.times { + println "hi" +} +// the CommandLine that parsed the args is available as a property +assert this.commandLine.commandName == "myScript"
@@ -17710,7 +17435,7 @@

30.1.2. G When upgrading scripts from picocli versions older than 4.0, just changing the version number is not enough! -Scripts should use @Grab('info.picocli:picocli-groovy:4.6.2'). The old artifact id @Grab('info.picocli:picocli:4.6.2') will not work, +Scripts should use @Grab('info.picocli:picocli-groovy:4.6.3-SNAPSHOT'). The old artifact id @Grab('info.picocli:picocli:4.6.3-SNAPSHOT') will not work, because the @picocli.groovy.PicocliScript annotation class and supporting classes have been moved into a separate module, picocli-groovy. @@ -17728,31 +17453,31 @@

-
@Command(name = "ClosureDemo",
-        versionProvider = {
-            { -> ["line1" , "line2"] as String[] } as IVersionProvider (1)
-        },
-        defaultValueProvider = {
-            { argSpec -> "some default" } as IDefaultValueProvider (2)
-        })
-class ClosureDemo {
-    @Option(names = '-x', completionCandidates = {["A", "B", "C"]}) (3)
-    String x
-
-    @Option(names = '-y',
-            parameterConsumer = {
-                { args, argSpec, commandSpec ->  (4)
-                    argSpec.setValue(args.toString() + commandSpec.name())
-                    args.clear()
-                } as IParameterConsumer
-            })
-    String y
-
-    @Option(names = '-z', converter = [ // requires Groovy 3.0.7
-            { { str -> MessageDigest.getInstance(str) } as ITypeConverter } (5)
-    ])
-    MessageDigest z
-}
+
@Command(name = "ClosureDemo",
+        versionProvider = {
+            { -> ["line1" , "line2"] as String[] } as IVersionProvider (1)
+        },
+        defaultValueProvider = {
+            { argSpec -> "some default" } as IDefaultValueProvider (2)
+        })
+class ClosureDemo {
+    @Option(names = '-x', completionCandidates = {["A", "B", "C"]}) (3)
+    String x
+
+    @Option(names = '-y',
+            parameterConsumer = {
+                { args, argSpec, commandSpec ->  (4)
+                    argSpec.setValue(args.toString() + commandSpec.name())
+                    args.clear()
+                } as IParameterConsumer
+            })
+    String y
+
+    @Option(names = '-z', converter = [ // requires Groovy 3.0.7
+            { { str -> MessageDigest.getInstance(str) } as ITypeConverter } (5)
+    ])
+    MessageDigest z
+}

@@ -17867,23 +17592,23 @@

-
@Command(name = "MyApp", version = arrayOf("picocli demo for Kotlin v1.0 and Kotlin v1.1"),
-        mixinStandardHelpOptions = true, // add --help and --version options
-        description = arrayOf("@|bold Kotlin|@ @|underline picocli|@ example"))
-class MyApp : Callable<Int> {
+
@Command(name = "MyApp", version = arrayOf("picocli demo for Kotlin v1.0 and Kotlin v1.1"),
+        mixinStandardHelpOptions = true, // add --help and --version options
+        description = arrayOf("@|bold Kotlin|@ @|underline picocli|@ example"))
+class MyApp : Callable<Int> {
 
-    @Option(names = arrayOf("-c", "--count"),
-            description = arrayOf("number of repetitions"))
-    private var count: Int = 1
+    @Option(names = arrayOf("-c", "--count"),
+            description = arrayOf("number of repetitions"))
+    private var count: Int = 1
 
-    override fun call(): Int {
-        for (i in 0 until count) {
-            println("hello world $i...")
-        }
-        return 0
-    }
-}
-fun main(args: Array<String>) = System.exit(CommandLine(MyApp()).execute(*args))
+ override fun call(): Int { + for (i in 0 until count) { + println("hello world $i...") + } + return 0 + } +} +fun main(args: Array<String>) = System.exit(CommandLine(MyApp()).execute(*args))
-
@Command(name = "MyApp", version = Array("Scala picocli demo v4.0"),
-         mixinStandardHelpOptions = true, // add --help and --version options
-         description = Array("@|bold Scala|@ @|underline picocli|@ example"))
-class MyApp extends Callable[Int] {
+
@Command(name = "MyApp", version = Array("Scala picocli demo v4.0"),
+         mixinStandardHelpOptions = true, // add --help and --version options
+         description = Array("@|bold Scala|@ @|underline picocli|@ example"))
+class MyApp extends Callable[Int] {
 
-    @Option(names = Array("-c", "--count"), paramLabel = "COUNT",
-            description = Array("the count"))
-    private var count: Int = 1
+    @Option(names = Array("-c", "--count"), paramLabel = "COUNT",
+            description = Array("the count"))
+    private var count: Int = 1
 
-    def call() : Int = {
-        for (i <- 0 until count) {
-            println(s"hello world $i...")
-        }
-        0
-    }
-}
-object MyApp {
-    def main(args: Array[String]): Unit = {
-        System.exit(new CommandLine(new MyApp()).execute(args: _*))
-    }
-}
+ def call() : Int = { + for (i <- 0 until count) { + println(s"hello world $i...") + } + 0 + } +} +object MyApp { + def main(args: Array[String]): Unit = { + System.exit(new CommandLine(new MyApp()).execute(args: _*)) + } +}
@@ -17996,63 +17721,63 @@

37.1. Build too
Gradle
-
implementation 'info.picocli:picocli:4.6.2'
+
implementation 'info.picocli:picocli:4.6.3-SNAPSHOT'
Gradle (Kotlin)
-
dependencies {
-    implementation("info.picocli:picocli:4.6.2")
-}
+
dependencies {
+    implementation("info.picocli:picocli:4.6.3-SNAPSHOT")
+}
Maven
-
<dependency>
-  <groupId>info.picocli</groupId>
-  <artifactId>picocli</artifactId>
-  <version>4.6.2</version>
-</dependency>
+
<dependency>
+  <groupId>info.picocli</groupId>
+  <artifactId>picocli</artifactId>
+  <version>4.6.3-SNAPSHOT</version>
+</dependency>
Scala SBT
-
libraryDependencies += "info.picocli" % "picocli" % "4.6.2"
+
libraryDependencies += "info.picocli" % "picocli" % "4.6.3-SNAPSHOT"
Ivy
-
<dependency org="info.picocli" name="picocli" rev="4.6.2" />
+
<dependency org="info.picocli" name="picocli" rev="4.6.3-SNAPSHOT" />
Grape
@Grapes(
-    @Grab(group='info.picocli', module='picocli', version='4.6.2')
+    @Grab(group='info.picocli', module='picocli', version='4.6.3-SNAPSHOT')
 )
Leiningen
-
[info.picocli/picocli "4.6.2"]
+
[info.picocli/picocli "4.6.3-SNAPSHOT"]
Buildr
-
'info.picocli:picocli:jar:4.6.2'
+
'info.picocli:picocli:jar:4.6.3-SNAPSHOT'
JBang
-
//DEPS info.picocli:picocli:4.6.2
+
//DEPS info.picocli:picocli:4.6.3-SNAPSHOT

@@ -18069,8 +17794,8 @@

37.2. Source

diff --git a/src/test/java/picocli/ArgGroupTest.java b/src/test/java/picocli/ArgGroupTest.java index 2b98ac884..f8b6a66ac 100644 --- a/src/test/java/picocli/ArgGroupTest.java +++ b/src/test/java/picocli/ArgGroupTest.java @@ -4062,6 +4062,7 @@ static class MyArgGroup { MyArgGroup argGroup; } + @Ignore @Test public void testIssue1384() { Issue1384 obj = new Issue1384(); @@ -4071,59 +4072,246 @@ public void testIssue1384() { assertEquals(obj.argGroup.param2, "b"); } + + /** + * Tests issue 1409 https://github.com/remkop/picocli/issues/1409 + * This specific test supplies values to the group one values, leaving + * the group two values uninitialized. + *

+ * The test verifies that x, 1A, 1B, 2A, and 2B values are correct after + * building the command using CommandLine.java and parsing the arguments. + * @author remkop, madfoal + */ @Command(name = "Issue-1409") - static class Issue1409 { + static class Issue1409 implements Runnable{ @ArgGroup(exclusive = false, heading = "%nOptions to be used with group 1 OR group 2 options.%n") - OptXAndGroupOneOrGroupTwo optXAndGroupOneOrGroupTwo = new OptXAndGroupOneOrGroupTwo(); + OptXAndGroupOneOrGroupTwo optXAndGroupOneOrGroupTwo; static class OptXAndGroupOneOrGroupTwo { @Option(names = { "-x", "--option-x" }, required = true, defaultValue = "Default X", description = "option X") String x; @ArgGroup(exclusive = true) - OneOrTwo oneORtwo = new OneOrTwo(); + OneOrTwo oneORtwo; } static class OneOrTwo { - public OneOrTwo() { - new Exception().printStackTrace(); - } @ArgGroup(exclusive = false, heading = "%nGroup 1%n%n") - GroupOne one = new GroupOne(); + GroupOne one; @ArgGroup(exclusive = false, heading = "%nGroup 2%n%n") - GroupTwo two = new GroupTwo(); + GroupTwo two; } static class GroupOne { @Option(names = { "-1a", "--option-1a" },required=true,description = "option A of group 1") - String _1a; + String a1; @Option(names = { "-1b", "--option-1b" },required=true,description = "option B of group 1") - String _1b; + String b1; } static class GroupTwo { @Option(names = { "-2a", "--option-2a" },required=true, defaultValue = "Default 2A", description = "option A of group 2") - private String _2a; + private String a2 = "Default 2A"; @Option(names = { "-2b", "--option-2b" },required=true, defaultValue = "Default 2B", description = "option B of group 2") - private String _2b; + private String b2 = "Default 2B"; + } + public void run() { + if (optXAndGroupOneOrGroupTwo == null) { + optXAndGroupOneOrGroupTwo = new OptXAndGroupOneOrGroupTwo(); + } + if (optXAndGroupOneOrGroupTwo.oneORtwo == null) { + optXAndGroupOneOrGroupTwo.oneORtwo = new OneOrTwo(); + } + if (optXAndGroupOneOrGroupTwo.oneORtwo.one == null) { + optXAndGroupOneOrGroupTwo.oneORtwo.one = new GroupOne(); + } + if (optXAndGroupOneOrGroupTwo.oneORtwo.two == null) { + optXAndGroupOneOrGroupTwo.oneORtwo.two = new GroupTwo(); + } + } } + + + // String literals for Issue 1409 + final String sampleX = "ANOTHER VALUE"; + final String errorX = "Default value for X incorrect"; + final String errorA1 = "Default value for a1 incorrect"; + final String errorB1 = "Default value for b1 incorrect"; + final String errorA2 = "Default value for a2 incorrect"; + final String errorB2 = "Default value for b2 incorrect"; - @Ignore + /** + * Tests issue 1409 https://github.com/remkop/picocli/issues/1409 + * This specific test supplies values to the group one values, leaving + * the group two values uninitialized. + *

+ * The test verifies that x, 1A, 1B, 2A, and 2B values are correct after + * building the command using CommandLine.java and executing the arguments. + * @author remkop, madfoal + */ @Test public void testIssue1409() { - Issue1409 obj = new Issue1409(); -// new CommandLine(obj).parseArgs("-x", "ANOTHER_VALUE", "-2a=x", "-2b=z"); - new CommandLine(obj).parseArgs("-x", "ANOTHER_VALUE"); - assertEquals("ANOTHER_VALUE", obj.optXAndGroupOneOrGroupTwo.x); - assertEquals(null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one._1a); - assertEquals(null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one._1b); - assertEquals("Default 2A", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two._2a); - assertEquals("Default 2B", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two._2b); + final Issue1409 obj = new Issue1409(); + new CommandLine(obj).execute("-x", sampleX); + assertEquals(errorX,sampleX, obj.optXAndGroupOneOrGroupTwo.x); + assertEquals(errorA1,null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.a1); + assertEquals(errorB1,null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.b1); + assertEquals(errorA2,"Default 2A", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.a2); + assertEquals(errorB2,"Default 2B", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.b2); + } + + /** + * Tests issue 1409 https://github.com/remkop/picocli/issues/1409 + * This specific test supplies values to the group one values, leaving + * the group two values uninitialized. + *

+ * The test verifies that x, 1A, 1B, 2A, and 2B values are correct after + * building the command using CommandLine.java and executing the arguments. + * @author madfoal + */ + @Test + public void testIssue1409InitializeGroup1() { + final Issue1409 obj = new Issue1409(); + new CommandLine(obj).execute("-x", sampleX, "-1a=x", "-1b=z"); + assertEquals(errorX,sampleX, obj.optXAndGroupOneOrGroupTwo.x); + assertEquals(errorA1,"x", obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.a1); + assertEquals(errorB1,"z", obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.b1); + assertEquals(errorA2,"Default 2A", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.a2); + assertEquals(errorB2,"Default 2B", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.b2); + } + + /** + * Tests issue 1409 https://github.com/remkop/picocli/issues/1409 + * This specific test supplies values to the group two values, leaving + * the group one values uninitialized. + *

+ * The test verifies that x, 1A, 1B, 2A, and 2B values are correct after + * building the command using CommandLine.java and executing the arguments. + * @author madfoal + */ + @Test + public void testIssue1409InitializeGroup2() { + final Issue1409 obj = new Issue1409(); + new CommandLine(obj).execute("-x", sampleX, "-2a=x", "-2b=z"); + assertEquals(errorX,sampleX, obj.optXAndGroupOneOrGroupTwo.x); + assertEquals(errorA1,null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.a1); + assertEquals(errorB1,null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.b1); + assertEquals(errorA2,"x", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.a2); + assertEquals(errorB2,"z", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.b2); + } + + /** + * Tests issue 1409 https://github.com/remkop/picocli/issues/1409 + * This specific test supplies values to the group one values, leaving + * the group two values uninitialized. + *

+ * The test verifies that x, 1A, 1B, 2A, and 2B values are correct after + * building the command using CommandLine.java and parsing the arguments. + * @author remkop, madfoal + */ + @Command(name = "Issue-1409-Mod") + static class Issue1409Mod{ - } -} + @ArgGroup(exclusive = false, heading = "%nOptions to be used with group 1 OR group 2 options.%n") + OptXAndGroupOneOrGroupTwo optXAndGroupOneOrGroupTwo = new OptXAndGroupOneOrGroupTwo(); + + static class OptXAndGroupOneOrGroupTwo { + @Option(names = { "-x", "--option-x" }, required = true, defaultValue = "Default X", description = "option X") + String x; + + @ArgGroup(exclusive = true) + OneOrTwo oneORtwo = new OneOrTwo(); + } + + static class OneOrTwo { + @ArgGroup(exclusive = false, heading = "%nGroup 1%n%n") + GroupOne one = new GroupOne(); + + @ArgGroup(exclusive = false, heading = "%nGroup 2%n%n") + GroupTwo two = new GroupTwo(); + } + + static class GroupOne { + @Option(names = { "-1a", "--option-1a" },required=true,description = "option A of group 1") + String a1; + + @Option(names = { "-1b", "--option-1b" },required=true,description = "option B of group 1") + String b1; + } + + static class GroupTwo { + @Option(names = { "-2a", "--option-2a" },required=true, defaultValue = "Default 2A", description = "option A of group 2") + private String a2 = "Default 2A"; // default value declared + + @Option(names = { "-2b", "--option-2b" },required=true, defaultValue = "Default 2B", description = "option B of group 2") + private String b2 = "Default 2B"; // default value declared + } + + } + + /** + * Tests issue 1409 https://github.com/remkop/picocli/issues/1409 + * This specific test supplies values to the group one values, leaving + * the group two values uninitialized. + *

+ * The test verifies that x, 1A, 1B, 2A, and 2B values are correct after + * building the command using CommandLine.java and parsing the arguments. + * @author remkop, madfoal + */ + @Test + public void testIssue1409Mod() { + final Issue1409Mod obj = new Issue1409Mod(); + new CommandLine(obj).parseArgs("-x", sampleX); + assertEquals(errorX,sampleX, obj.optXAndGroupOneOrGroupTwo.x); + assertEquals(errorA1,null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.a1); + assertEquals(errorB1,null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.b1); + assertEquals(errorA2,"Default 2A", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.a2); + assertEquals(errorB2,"Default 2B", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.b2); + } + + /** + * Tests issue 1409 https://github.com/remkop/picocli/issues/1409 + * This specific test supplies values to the group one values, leaving + * the group two values uninitialized. + *

+ * The test verifies that x, 1A, 1B, 2A, and 2B values are correct after + * building the command using CommandLine.java and parsing the arguments. + * @author madfoal + */ + @Test + public void testIssue1409ModInitializeGroup1() { + final Issue1409Mod obj = new Issue1409Mod(); + new CommandLine(obj).parseArgs("-x", sampleX, "-1a=x", "-1b=z"); + assertEquals(errorX,sampleX, obj.optXAndGroupOneOrGroupTwo.x); + assertEquals(errorA1,"x", obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.a1); + assertEquals(errorB1,"z", obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.b1); + assertEquals(errorA2,"Default 2A", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.a2); + assertEquals(errorB2,"Default 2B", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.b2); + } + + /** + * Tests issue 1409 https://github.com/remkop/picocli/issues/1409 + * This specific test supplies values to the group two values, leaving + * the group one values uninitialized. + *

+ * The test verifies that x, 1A, 1B, 2A, and 2B values are correct after + * building the command using CommandLine.java and parsing the arguments. + * @author madfoal + */ + @Test + public void testIssue1409ModInitializeGroup2() { + final Issue1409Mod obj = new Issue1409Mod(); + new CommandLine(obj).parseArgs("-x", sampleX, "-2a=x", "-2b=z"); + assertEquals(errorX,sampleX, obj.optXAndGroupOneOrGroupTwo.x); + assertEquals(errorA1,null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.a1); + assertEquals(errorB1,null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one.b1); + assertEquals(errorA2,"x", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.a2); + assertEquals(errorB2,"z", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two.b2); + } + +} \ No newline at end of file