### init Method Implementation Example Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.IHelpCommandInitializable2.html An example of how the init method might be implemented to initialize a custom help command. ```java void init(CommandLine helpCommandLine, CommandLine.Help.ColorScheme colorScheme, PrintWriter outWriter, PrintWriter errWriter) ``` -------------------------------- ### Example Command with PropertiesDefaultProvider Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.PropertiesDefaultProvider.html This example shows how to configure a command to use PropertiesDefaultProvider. The provider will look for a properties file named '.git.properties' in the user's home directory. ```java @Command(name = "git", defaultValueProvider = PropertiesDefaultProvider.class) class Git { } ``` -------------------------------- ### Modern execute method example Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.html This example demonstrates the recommended `execute` method for running commands, showing how to configure output, error streams, and color schemes before execution. ```java CommandLine cmd = new CommandLine(runnable) .setOut(myOutWriter()) // System.out by default .setErr(myErrWriter()) // System.err by default .setColorScheme(myColorScheme()); // default color scheme, Ansi.AUTO by default int exitCode = cmd.execute(args); //System.exit(exitCode); ``` -------------------------------- ### Example Resource Bundle Properties Source: https://picocli.info/index.html This example demonstrates how to structure a Java properties file for internationalized messages in Picocli, including usage help sections and option descriptions. ```properties # Usage Help Message Sections # --------------------------- # Numbered resource keys can be used to create multi-line sections. usage.headerHeading = This is my app. It does stuff. Good stuff.%n usage.header = header first line usage.header.0 = header second line usage.descriptionHeading = Description:%n usage.description.0 = first line usage.description.1 = second line usage.description.2 = third line usage.synopsisHeading = Usage:\u0020 # Leading whitespace is removed by default. # Start with \u0020 to keep the leading whitespace. usage.customSynopsis.0 = Usage: ln [OPTION]... [-T] TARGET LINK_NAME (1st form) usage.customSynopsis.1 = \u0020 or: ln [OPTION]... TARGET (2nd form) usage.customSynopsis.2 = \u0020 or: ln [OPTION]... TARGET... DIRECTORY (3rd form) # Headings can contain the %n character to create multi-line values. usage.parameterListHeading = %nPositional parameters:%n usage.optionListHeading = %nOptions:%n usage.commandListHeading = %nCommands:%n usage.footerHeading = Powered by picocli%n usage.footer = footer # Option Descriptions # ------------------- # Use numbered keys to create multi-line descriptions. # Example description for an option `@Option(names = "-x")` x = This is the description for the -x option # Example multi-line description for an option `@Option(names = "-y")` y.0 = This is the first line of the description for the -y option y.1 = This is the second line of the description for the -y option # Example descriptions for the standard help mixin options: help = Show this help message and exit. version = Print version information and exit. # Exit Code Description # --------------------- usage.exitCodeListHeading = Exit Codes:%n usage.exitCodeList.0 = \u00200:Successful program execution. (notice leading space '\u0020') usage.exitCodeList.1 = 64:Usage error: user input for the command was incorrect. usage.exitCodeList.2 = 70:An exception occurred when invoking the business logic of this command. # @file Description # ----------------- picocli.atfile=One or more argument files containing options, commands and positional parameters. # End-of-Options (--) Delimiter Description ``` -------------------------------- ### Create Example File Source: https://picocli.info/index.html Create a sample text file for testing checksum applications. ```bash echo "hello" > hello.txt ``` -------------------------------- ### Example Command Line Invocations Source: https://picocli.info/index.html Demonstrates how to invoke commands with mixin options from the command line. These examples show the flexibility of using mixins for shared options like verbosity. ```bash java Top -v java Top -v sub java Top sub -v ``` -------------------------------- ### Picocli Command Line Application Example Source: https://picocli.info/apidocs-all/info.picocli/module-summary.html This example demonstrates a basic picocli application using `CommandLine.execute` for parsing arguments, error handling, and generating help/version messages in a single line of code. It defines a `CheckSum` command with parameters and options. ```java @Command(name = "checksum", mixinStandardHelpOptions = true, version = "Checksum 4.0", description = "Prints the checksum (SHA-1 by default) of a file to STDOUT.") class CheckSum implements Callable { @Parameters(index = "0", description = "The file whose checksum to calculate.") private File file; @Option(names = {"-a", "--algorithm"}, description = "MD5, SHA-1, SHA-256, ...") private String algorithm = "SHA-1"; @Override public Integer call() throws Exception { // your business logic goes here byte[] fileContents = Files.readAllBytes(file.toPath()); byte[] digest = MessageDigest.getInstance(algorithm).digest(fileContents); System.out.printf("%0" + (digest.length*2) + "x%n", new BigInteger(1, digest)); return 0; } // CheckSum implements Callable, so parsing, error handling and handling user // requests for usage help or version help can be done with one line of code. public static void main(String[] args) { int exitCode = new CommandLine(new CheckSum()).execute(args); System.exit(exitCode); } } ``` -------------------------------- ### Kotlin Example with Repeatable Subcommands Source: https://picocli.info/index.html Shows the equivalent of the Java example in Kotlin, using `subcommandsRepeatable = true` for the `myapp` command to enable multiple subcommand invocations. ```Kotlin @Command(name = "myapp", subcommandsRepeatable = true) class MyApp : Runnable { @Command fun add(@Option(names = ["-x"]) x: String, @Option(names = ["-w"]) w: Double) { ... } @Command fun list(@Option(names = ["--where"]) where: String) { ... } @Command(name = "send-report") fun sendReport(@Option(names = ["--to"], split = ",") recipients: Array) { ... } companion object { @JvmStatic fun main(args: Array) { CommandLine(MyApp()).execute(*args) } } } ``` -------------------------------- ### Equivalent Command Line Argument Invocation Examples Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.html These examples illustrate various equivalent ways to invoke the Encrypt program with command-line arguments, demonstrating different syntaxes for options and parameters. ```bash --verbose --out=outfile in1 in2 --verbose --out outfile in1 in2 -v --out=outfile in1 in2 -v -o outfile in1 in2 -v -o=outfile in1 in2 -vo outfile in1 in2 -vo=outfile in1 in2 -v -ooutfile in1 in2 -vooutfile in1 in2 ``` -------------------------------- ### Example Properties File for Git Command Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.PropertiesDefaultProvider.html This example shows how to define default values for a subcommand's options in a properties file. The key is prefixed with the command's qualified name. ```properties # /home/remko/.git.properties git.commit.cleanup = strip ``` -------------------------------- ### Kotlin Example: Top-level command with subcommands Source: https://picocli.info/index.html This Kotlin example illustrates defining nested commands and subcommands using Kotlin's syntax and features with Picocli. ```kotlin @Command(name = "foo", subcommands = [Bar::class]) class Foo : Callable { @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 } } fun main(args: Array) : Unit = exitProcess(CommandLine(Foo()).execute(*args)) @Command(name = "bar", description = ["I'm a subcommand of `foo`"]) class Bar : Callable { @Option(names = ["-y"]) var y: Int = 0 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 } } ``` -------------------------------- ### Picocli Tracing Output Example Source: https://picocli.info/quick-guide.html Example output demonstrating the INFO level tracing for command line argument parsing, including field population and parameter handling. ```text [picocli INFO] Parsing 8 command line args [--git-dir=/home/rpopma/picocli, commit, -m, "Fixed typos", --, src1.java, src2.java, src3.java] [picocli INFO] Setting File field 'Git.gitDir' to '\home\rpopma\picocli' for option --git-dir [picocli INFO] Adding [Fixed typos] to List field 'GitCommit.message' for option -m [picocli INFO] Found end-of-options delimiter '--'. Treating remainder as positional parameters. [picocli INFO] Adding [src1.java] to List field 'GitCommit.files' for args[0..*] [picocli INFO] Adding [src2.java] to List field 'GitCommit.files' for args[0..*] [picocli INFO] Adding [src3.java] to List field 'GitCommit.files' for args[0..*] ``` -------------------------------- ### Customized Usage Message Example Source: https://picocli.info/index.html This example shows a customized usage message for a git commit-like command. It includes a detailed description, parameters, and options, demonstrating how to format a comprehensive help output. ```text Usage: Record changes to the repository. git commit [-ap] [--fixup=] [--squash=] [-c=] [-C=] [-F=] [-m[=...]] [...] Description: Stores the current contents of the index in a new commit along with a log message from the user describing the changes. Parameters: the files to commit Options: -a, --all Tell the command to automatically stage files that have been modified and deleted, but new files you have not told Git about are not affected. -p, --patch Use the interactive patch selection interface to chose which changes to commit -C, --reuse-message= Take an existing commit object, and reuse the log message and the authorship information (including the timestamp) when creating the commit. -c, --reedit-message= Like -C, but with -c the editor is invoked, so that the user can further edit the commit message. --fixup= Construct a commit message for use with rebase --autosquash. --squash= Construct a commit message for use with rebase --autosquash. The commit message subject line is taken from the specified commit with a prefix of "squash! ". Can be used with additional commit message options (-m/-c/-C/-F). -F, --file= Take the commit message from the given file. Use - to read the message from the standard input. -m, --message[=...] Use the given as the commit message. If multiple -m options are given, their values are concatenated as separate paragraphs. ``` -------------------------------- ### Examples of Custom Parsing Usage Source: https://picocli.info/index.html Illustrates various command-line inputs that are valid when using a custom parameter consumer for an option like '-x'. These examples show passing option names, subcommands, or quoted values as parameters. ```Shell java App -x=mySubcommand ``` ```Shell java App -x mySubcommand ``` ```Shell java App -x=-y ``` ```Shell java App -x -y -y=123 ``` -------------------------------- ### Get expandAtFiles Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Model.ParserSpec.html Retrieves the boolean value indicating whether to expand arguments starting with '@' as file paths. ```java public boolean expandAtFiles() ``` -------------------------------- ### Get End-of-Options Delimiter Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.html Retrieves the delimiter that signifies the end of options and the start of positional parameters. The default is '--'. ```java public String getEndOfOptionsDelimiter() ``` -------------------------------- ### init() Method Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.HelpCommand.html Initializes the help command with a color scheme for customized output. ```APIDOC ## init(CommandLine helpCommandLine, CommandLine.Help.ColorScheme colorScheme, PrintWriter out, PrintWriter err) ### Description Initializes this object with the information needed to implement a help command that provides usage help for other commands. Specified by: `init` in interface `CommandLine.IHelpCommandInitializable2` ### Parameters * `helpCommandLine` (CommandLine) - the `CommandLine` object associated with this help command. Implementors can use this to walk the command hierarchy and get access to the help command's parent and sibling commands. * `colorScheme` (CommandLine.Help.ColorScheme) - the color scheme to use when printing help, including whether to use Ansi colors or not * `out` (PrintWriter) - the output writer to print the usage help message to * `err` (PrintWriter) - the error writer to print any diagnostic messages to, in addition to the output from the exception handler ### Method `void init(CommandLine helpCommandLine, CommandLine.Help.ColorScheme colorScheme, PrintWriter out, PrintWriter err) ``` -------------------------------- ### Basic PicocliScript2 Usage in Groovy Source: https://picocli.info/apidocs-all/info.picocli.groovy/picocli/groovy/PicocliScript2.html Example of using @PicocliScript2 with @Command and @Option annotations in a Groovy script. This setup automatically handles command-line parsing and help messages. ```groovy @Command(name = "myCommand", description = "does something special") @PicocliScript2 import picocli.groovy.PicocliScript2 import picocli.CommandLine.Command import picocli.CommandLine.Option import groovy.transform.Field @Option(names = "-x", description = "number of repetitions") @Field int count; @Option(names = ["-h", "--help"], usageHelp = true, description = "print this help message and exit") @Field boolean helpRequested; //if (helpRequested) { CommandLine.usage(this, System.err); return 0; } // PicocliBaseScript takes care of this count.times { println "hi" } assert this == theScript assert this.commandLine.commandName == "myCommand" ``` -------------------------------- ### picocli.CommandLine.IHelpCommandInitializable2.init(CommandLine, CommandLine.Help.ColorScheme, PrintWriter, PrintWriter) Source: https://picocli.info/apidocs-all/index-files/index-9.html Initializes this object with the information needed to implement a help command that provides usage help for other commands. ```APIDOC ## init(CommandLine, CommandLine.Help.ColorScheme, PrintWriter, PrintWriter) ### Description Initializes this object with the information needed to implement a help command that provides usage help for other commands. ### Method `init(CommandLine commandLine, CommandLine.Help.ColorScheme colorScheme, PrintWriter writer, PrintWriter err)` ### Interface `picocli.CommandLine.IHelpCommandInitializable2` ``` -------------------------------- ### Get Argument File Comment Character Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.html Retrieves the character that signifies the start of a single-line comment within argument files. If null, all content in argument files is interpreted as arguments. The default comment character is '#'. ```java public Character getAtFileCommentChar() { // ... } ``` -------------------------------- ### Field Injection Example Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Spec.html Example of injecting CommandSpec into a field. The annotated field will be initialized with the CommandSpec for the command. ```java class InjectSpecExample implements Runnable { @Spec CommandSpec commandSpec; //... public void run() { // do something with the injected objects } } ``` -------------------------------- ### Example Properties Resource Bundle for Usage Help Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Model.Messages.html This snippet shows how to structure a properties file for picocli's usage help messages. It demonstrates multi-line sections using numbered keys and how to format headings and descriptions. ```properties # Usage Help Message Sections # --------------------------- # Numbered resource keys can be used to create multi-line sections. usage.headerHeading = This is my app. There are other apps like it but this one is mine.%n usage.header = header first line usage.header.0 = header second line usage.descriptionHeading = Description:%n usage.description.0 = first line usage.description.1 = second line usage.description.2 = third line usage.synopsisHeading = Usage:\u0020 # Leading whitespace is removed by default. Start with \u0020 to keep the leading whitespace. usage.customSynopsis.0 = Usage: ln [OPTION]... [-T] TARGET LINK_NAME (1st form) usage.customSynopsis.1 = \u0020 or: ln [OPTION]... TARGET (2nd form) usage.customSynopsis.2 = \u0020 or: ln [OPTION]... TARGET... DIRECTORY (3rd form) # Headings can contain the %n character to create multi-line values. usage.parameterListHeading = %nPositional parameters:%n usage.optionListHeading = %nOptions:%n usage.commandListHeading = %nCommands:%n usage.footerHeading = Powered by picocli%n usage.footer = footer # Option Descriptions # ------------------- # Use numbered keys to create multi-line descriptions. help = Show this help message and exit. version = Print version information and exit. ``` -------------------------------- ### picocli.CommandLine.HelpCommand.init(CommandLine, CommandLine.Help.ColorScheme, PrintWriter, PrintWriter) Source: https://picocli.info/apidocs-all/index-files/index-9.html Initializes this object with the information needed to implement a help command that provides usage help for other commands. ```APIDOC ## init(CommandLine, CommandLine.Help.ColorScheme, PrintWriter, PrintWriter) ### Description Initializes this object with the information needed to implement a help command that provides usage help for other commands. ### Method `init(CommandLine commandLine, CommandLine.Help.ColorScheme colorScheme, PrintWriter writer, PrintWriter err)` ### Class `picocli.CommandLine.HelpCommand` ``` -------------------------------- ### Substring Method (start) Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Help.Ansi.Text.html Returns a new Text instance that is a substring of the current Text, starting from the specified position. ```java public CommandLine.Help.Ansi.Text substring(int start) ``` -------------------------------- ### Example AbstractParseResultHandler Subclass Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.AbstractParseResultHandler.html An example of how to implement a subclass of AbstractParseResultHandler, demonstrating the use of the self() method for proper method chaining. ```java class MyResultHandler extends AbstractParseResultHandler { protected MyReturnType handle(ParseResult parseResult) throws ExecutionException { ... } protected MyResultHandler self() { return this; } } ``` -------------------------------- ### CommandLine.IHelpFactory.create(CommandLine.Model.CommandSpec, CommandLine.Help.ColorScheme) Source: https://picocli.info/apidocs-all/index-files/index-3.html Returns a `Help` instance to assist in rendering the usage help message. ```APIDOC ## CommandLine.IHelpFactory.create(CommandLine.Model.CommandSpec, CommandLine.Help.ColorScheme) ### Description Returns a `Help` instance to assist in rendering the usage help message. ### Method Instance method ### Parameters * **CommandLine.Model.CommandSpec** - The command specification. * **CommandLine.Help.ColorScheme** - The color scheme to use for help messages. ``` -------------------------------- ### Substring Method (start, end) Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Help.Ansi.Text.html Returns a new Text instance that is a substring of the current Text, from the specified start to end positions. ```java public CommandLine.Help.Ansi.Text substring(int start, int end) ``` -------------------------------- ### Example: Print help for a subcommand Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.HelpCommand.html Demonstrates how to invoke the help command to display usage information for a specific subcommand. ```bash command help subcommand ``` -------------------------------- ### Install Short Error Message Handler Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.html Demonstrates how to install a custom parameter exception handler, such as the ShortErrorMessageHandler, onto a CommandLine instance. ```java new CommandLine(new MyApp()) .setParameterExceptionHandler(new ShortErrorMessageHandler()) .execute(args); ``` -------------------------------- ### picocli.CommandLine.RunFirst.handleParseResult Source: https://picocli.info/apidocs-all/index-files/index-8.html Prints help if requested, and otherwise executes the top-level Runnable or Callable command. ```APIDOC ## handleParseResult(List, PrintStream, CommandLine.Help.Ansi) ### Description Prints help if requested, and otherwise executes the top-level `Runnable` or `Callable` command. ### Method N/A (Method signature) ### Endpoint N/A ### Parameters - **List** (List) - A list of command line objects. - **PrintStream** (PrintStream) - The stream to print messages to. - **Ansi** (CommandLine.Help.Ansi) - Ansi settings for output formatting. ### Request Example N/A ### Response N/A (Executes command) ``` -------------------------------- ### Example GraalVM Reflection Configuration JSON Source: https://picocli.info/picocli-on-graalvm.html This is an example of the JSON output generated by ReflectionConfigGenerator, detailing program elements accessed reflectively by picocli. ```json [ { "name" : "picocli.codegen.aot.graalvm.Example", "allDeclaredConstructors" : true, "allPublicConstructors" : true, "allDeclaredMethods" : true, "allPublicMethods" : true, "fields" : [ { "name" : "spec" }, { "name" : "unmatched" }, { "name" : "timeUnit" }, { "name" : "file" } ], "methods" : [ { "name" : "setMinimum", "parameterTypes" : ["int"] }, { "name" : "setOtherFiles", "parameterTypes" : ["[Ljava.io.File;"] }, { "name" : "multiply", "parameterTypes" : ["int", "int"] } ] }, ... ] ``` -------------------------------- ### Configure and Execute CommandLine Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.html Demonstrates how to configure a CommandLine instance with custom settings like case-insensitive enum values, output/error streams, and color schemes before executing it with provided arguments. ```java CommandLine cmd = new CommandLine(new MyCallable()) .setCaseInsensitiveEnumValuesAllowed(true) // configure a non-default parser option .setOut(myOutWriter()) // configure an alternative to System.out .setErr(myErrWriter()) // configure an alternative to System.err .setColorScheme(myColorScheme()); // configure a custom color scheme int exitCode = cmd.execute(args); System.exit(exitCode); ``` -------------------------------- ### substring(int start) Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Help.Ansi.Text.html Returns a new Text instance that is a substring of this Text, starting from the specified index. This method does not modify the original instance. ```APIDOC ## substring(int start) ### Description Returns a new `Text` instance that is a substring of this Text, starting from the specified index. This method does not modify the original instance. ### Method `public CommandLine.Help.Ansi.Text substring(int start)` ### Parameters #### Path Parameters - **start** (int) - The index in the plain text where to start the substring. ### Returns - **Text** - A new `Text` instance that is a substring of this `Text`. ``` -------------------------------- ### Get Cell at Specific Cell (Deprecated) Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Help.TextTable.html Deprecated method to get the Text object at a specific row and column. Use textAt instead. ```java @Deprecated public CommandLine.Help.Ansi.Text cellAt(int row, int col) ``` -------------------------------- ### HelpCommand init() Method Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.HelpCommand.html Initializes the help command with a color scheme and print writers for output and error streams. ```java public void init​(CommandLine helpCommandLine, CommandLine.Help.ColorScheme colorScheme, PrintWriter out, PrintWriter err) ``` -------------------------------- ### Dynamic Model Transformation Example (Kotlin) Source: https://picocli.info/index.html Example of a Kotlin class using a model transformer to conditionally remove a subcommand based on a system property. ```kotlin @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 } } @Command private fun sub() { // subcommand, business logic } } ``` -------------------------------- ### Create a Bash Script Wrapper Source: https://picocli.info/autocomplete.html This example shows how to create a simple bash script that wraps the execution of a picocli application, including its JARs, for easier command-line use. ```bash $ echo '#!/usr/bin/env bash' > jchecksum $ echo 'java -cp "picocli-1.0.0.jar;myproject.jar" com.myproject.CheckSum $@' >> jchecksum $ chmod 755 jchecksum $ cat jchecksum #!/usr/bin/env bash java -cp "picocli-1.0.0.jar;myproject.jar" com.myproject.CheckSum $@ ``` -------------------------------- ### Dynamic Model Transformation Example (Java) Source: https://picocli.info/index.html Example of a Java class using a model transformer to conditionally remove a subcommand based on a system property. ```java @Command(modelTransformer = Dynamic.SubCmdFilter.class) class Dynamic { static class SubCmdFilter implements IModelTransformer { public CommandSpec transform(CommandSpec commandSpec) { if (Boolean.getBoolean("disable_sub")) { commandSpec.removeSubcommand("sub"); } return commandSpec; } } @Command private void sub() { // subcommand, business logic } } ``` -------------------------------- ### main Method Source: https://picocli.info/apidocs-all/info.picocli.codegen/picocli/codegen/aot/graalvm/DynamicProxyConfigGenerator.html Runs the DynamicProxyConfigGenerator as a standalone application to generate and print proxy configuration. ```APIDOC ## main(String... args) ### Description Runs this class as a standalone application, printing the resulting JSON String to a file or to `System.out`. ### Parameters - `args` (String...) - one or more fully qualified class names of `@Command`-annotated classes. ### Method `public static void main(String... args)` ``` -------------------------------- ### Example Input for Repeating Positional Parameters Source: https://picocli.info/index.html This is an example of the command-line input expected for an application using repeating positional parameters within an argument group. ```text Alice 3.1 Betty 4.0 "X Æ A-12" 3.5 Zaphod 3.4 ``` -------------------------------- ### Picocli Groovy Script Example Source: https://picocli.info/apidocs-all/info.picocli.groovy/picocli/groovy/PicocliBaseScript2.html Example of a Groovy script using PicocliBaseScript2 for command-line argument processing. It demonstrates the @Command, @PicocliScript2, and @Option annotations. ```groovy @Command(name = "greet", description = "Says hello.", mixinStandardHelpOptions = true, version = "greet 0.1") @PicocliScript2 import picocli.groovy.PicocliScript2 import picocli.CommandLine.Command import picocli.CommandLine.Option import groovy.transform.Field @Option(names = ['-g', '--greeting'], description = 'Type of greeting') @Field String greeting = 'Hello' println "${greeting} world!" ``` -------------------------------- ### IHelpFactory.create Source: https://picocli.info/apidocs-all/info.picocli/picocli/class-use/CommandLine.Model.CommandSpec.html Creates a Help instance for rendering usage messages, using the provided CommandSpec and ColorScheme. ```APIDOC ## IHelpFactory.create ### Description Returns a `Help` instance to assist in rendering the usage help message. ### Method `CommandLine.Help` ### Parameters - `commandSpec` (CommandLine.Model.CommandSpec) - The CommandSpec to use for help generation. - `colorScheme` (CommandLine.Help.ColorScheme) - The color scheme for rendering help. ``` -------------------------------- ### Set up Git Alias Source: https://picocli.info/quick-guide.html This is an example of how to set up an alias for a Java application that uses Picocli for command-line argument parsing. ```bash alias git='java picocli.Demo$Git' ``` -------------------------------- ### CommandLine.IHelpCommandInitializable Source: https://picocli.info/apidocs-all/info.picocli/picocli/package-use.html Deprecated. use `CommandLine.IHelpCommandInitializable2` instead ```APIDOC ## CommandLine.IHelpCommandInitializable ### Description Deprecated. use `CommandLine.IHelpCommandInitializable2` instead. ### Interface `CommandLine.IHelpCommandInitializable` ``` -------------------------------- ### Scala Example: Top-level command with subcommands Source: https://picocli.info/index.html This Scala example demonstrates how to implement nested commands and subcommands using Scala's syntax with the Picocli library. ```scala @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 } } 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 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 } } ``` -------------------------------- ### Help(CommandLine.Model.CommandSpec, CommandLine.Help.ColorScheme) - Picocli.CommandLine.Help Constructor Source: https://picocli.info/apidocs-all/index-files/index-8.html Constructs a new Help instance with a specified color scheme, initialized from a CommandSpec. ```APIDOC ## Help(CommandLine.Model.CommandSpec commandSpec, CommandLine.Help.ColorScheme colorScheme) ### Description Constructs a new `Help` instance with the specified color scheme, initialized from annotations on the specified class and superclasses. ### Method CONSTRUCTOR ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters - **commandSpec** (CommandLine.Model.CommandSpec) - Required - The CommandSpec to initialize Help from. - **colorScheme** (CommandLine.Help.ColorScheme) - Required - The color scheme to use. ### Response #### Success Response - **Help**: A new Help instance. ``` -------------------------------- ### CommandLine.IHelpFactory Source: https://picocli.info/apidocs-all/info.picocli/picocli/package-use.html Creates the `CommandLine.Help` instance used to render the usage help message. ```APIDOC ## CommandLine.IHelpFactory ### Description Creates the `CommandLine.Help` instance used to render the usage help message. ### Interface `CommandLine.IHelpFactory` ``` -------------------------------- ### Example: Print help for the parent command Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.HelpCommand.html Shows how to invoke the help command without any arguments to display usage information for the parent command. ```bash command help ``` -------------------------------- ### Using Custom Guice Factory with CommandLine (Kotlin) Source: https://picocli.info/index.html Kotlin example demonstrating the use of a custom Guice factory with picocli's CommandLine. It shows how to inject dependencies into a runnable command class. ```kotlin 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 @CommandLine.Option(names = ["-x"]) var x = 0 override fun run() { assert(list is kotlin.collections.ArrayList<*>) } } fun main(args: Array) { CommandLine(InjectionDemo::class.java, GuiceFactory()).execute(*args) } ``` -------------------------------- ### Example Short Error Message Handler Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.html An example implementation of a parameter exception handler that provides a concise error message, suggestions for mistyped arguments, and usage information. ```java static class ShortErrorMessageHandler implements IParameterExceptionHandler {  public int handleParseException(ParameterException ex, String[] args) {  CommandLine cmd = ex.getCommandLine();  PrintWriter writer = cmd.getErr();  writer.println(ex.getMessage());  UnmatchedArgumentException.printSuggestions(ex, writer);  writer.print(cmd.getHelp().fullSynopsis());  CommandSpec spec = cmd.getCommandSpec();  writer.printf("Try '%s --help' for more information.%n", spec.qualifiedName());  return cmd.getExitCodeExceptionMapper() != null  ? cmd.getExitCodeExceptionMapper().getExitCode(ex)  : spec.exitCodeOnInvalidInput();  }  }   ``` -------------------------------- ### init Method Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.IHelpCommandInitializable2.html Initializes a help command with necessary components for displaying usage information. This method is called by `CommandLine.printHelpIfRequested` before the help command's `run` or `call` method is invoked. ```APIDOC ## init Method ### Description Initializes this object with the information needed to implement a help command that provides usage help for other commands. ### Method void ### Signature `init(CommandLine helpCommandLine, CommandLine.Help.ColorScheme colorScheme, PrintWriter outWriter, PrintWriter errWriter)` ### Parameters #### Parameters - **helpCommandLine** (CommandLine) - Required - The `CommandLine` object associated with this help command. Implementors can use this to walk the command hierarchy and get access to the help command's parent and sibling commands. - **colorScheme** (CommandLine.Help.ColorScheme) - Required - The color scheme to use when printing help, including whether to use Ansi colors or not. - **outWriter** (PrintWriter) - Required - The output writer to print the usage help message to. - **errWriter** (PrintWriter) - Required - The error writer to print any diagnostic messages to, in addition to the output from the exception handler. ``` -------------------------------- ### Basic Command Line Parsing with Picocli Source: https://picocli.info/picocli-programmatic-api.html Demonstrates how to use picocli.CommandLine.parseArgs to parse command-line arguments programmatically. Handles usage help, version help, invalid input, and business logic execution. ```java public static void main(String... args) { int exitCode = myParse(args); System.exit(exitCode); } int myParse(String... args) { CommandSpec spec = CommandSpec.create(); // add options and positional parameters CommandLine cmd = new CommandLine(spec); 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 myBusinessLogic(parseResult); 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(); } } void myBusinessLogic(ParseResult pr) throws java.io.IOException { int count = pr.matchedOptionValue('c', 1); List files = pr.matchedPositionalValue(0, Collections.emptyList()); for (File f : files) { for (int i = 0; i < count; i++) { System.out.printf("%d: %s%n", i, f.getCanonicalFile()); } } } ``` -------------------------------- ### Groovy Example: Top-level command with subcommands Source: https://picocli.info/index.html Similar to the Java example, this Groovy code defines nested subcommands 'foo', 'bar', and 'baz', demonstrating Groovy syntax for Picocli. ```groovy @Command(name = "foo", subcommands = Bar.class) class Foo implements Callable { @Option(names = "-x") def x @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) } } @Command(name = "bar", description = "I'm a subcommand of `foo`") class Bar implements Callable { @Option(names = "-y") int y @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 } } ``` -------------------------------- ### CommandLine.Help.TextTable(CommandLine.Help.ColorScheme, CommandLine.Help.Column[]) Source: https://picocli.info/apidocs-all/index-files/index-20.html Constructs a TextTable with the specified ColorScheme and columns. ```APIDOC ## TextTable(CommandLine.Help.ColorScheme, CommandLine.Help.Column[]) ### Description Constructs a TextTable with the specified ColorScheme and columns. ### Constructor `TextTable(picocli.CommandLine.Help.ColorScheme, picocli.CommandLine.Help.Column[])` ### Class picocli.CommandLine.Help.TextTable ``` -------------------------------- ### Using CDI Factory with Picocli Application Source: https://picocli.info/index.html Demonstrates how to instantiate a Picocli command using a custom CDI factory and execute it with provided arguments. ```java @Command(name = "cdi-app", mixinStandardHelpOptions = true) class MyCDIApp implements Runnable { boolean flag; @Option(names = {"-x", "--option"}, description = "example option") public void setFlag(boolean flag) { this.flag = flag; } @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); } } ``` -------------------------------- ### Custom Component Tracing Example Source: https://picocli.info/index.html Use the Tracer API within custom components, such as type converters, to log information during processing. This example shows tracing in a custom Integer converter. ```java class MyIntConverter implements ITypeConverter { public Integer convert(String value) { try { return Integer.parseInt(value); } catch (NumberFormatException ex) { CommandLine.tracer().info( "Could not convert %s to Integer, returning default value -1", value); return -1; } } } ``` -------------------------------- ### Alternative Command Execution Flow Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.html Demonstrates an alternative to the deprecated `invoke` method, showing how to manually create a CommandLine instance, configure it, and execute commands. ```java Method commandMethod = getCommandMethods(cls, methodName).get(0); CommandLine cmd = new CommandLine(commandMethod) .setOut(myOutWriter()) // System.out by default .setErr(myErrWriter()) // System.err by default .setColorScheme(myColorScheme()); // default color scheme, Ansi.AUTO by default int exitCode = cmd.execute(args); //System.exit(exitCode); ``` -------------------------------- ### Help(Object, CommandLine.Help.Ansi) - Picocli.CommandLine.Help Constructor Source: https://picocli.info/apidocs-all/index-files/index-8.html Constructs a new Help instance with a specified ANSI color scheme, initialized from annotations on the specified class. ```APIDOC ## Help(Object commandClass, CommandLine.Help.Ansi ansi) ### Description Constructs a new `Help` instance with a default color scheme, initialized from annotations on the specified class and superclasses. ### Method CONSTRUCTOR ### Endpoint N/A (Constructor) ### Parameters #### Path Parameters - **commandClass** (Object) - Required - The class containing command annotations. - **ansi** (CommandLine.Help.Ansi) - Required - The ANSI color scheme to use. ### Response #### Success Response - **Help**: A new Help instance. ``` -------------------------------- ### init() Method (Deprecated) Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.HelpCommand.html Deprecated method to initialize the help command with Ansi support. ```APIDOC ## init(CommandLine helpCommandLine, CommandLine.Help.Ansi ansi, PrintStream out, PrintStream err) ### Description Deprecated. Initializes this object with the information needed to implement a help command that provides usage help for other commands. Specified by: `init` in interface `CommandLine.IHelpCommandInitializable` ### Parameters * `helpCommandLine` (CommandLine) - the `CommandLine` object associated with this help command. Implementors can use this to walk the command hierarchy and get access to the help command's parent and sibling commands. * `ansi` (CommandLine.Help.Ansi) - whether to use Ansi colors or not * `out` (PrintStream) - the stream to print the usage help message to * `err` (PrintStream) - the error stream to print any diagnostic messages to, in addition to the output from the exception handler ### Method `void init(CommandLine helpCommandLine, CommandLine.Help.Ansi ansi, PrintStream out, PrintStream err) ``` -------------------------------- ### substring(int start, int end) Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Help.Ansi.Text.html Returns a new Text instance that is a substring of this Text, starting from the specified index and ending at the specified index. This method does not modify the original instance. ```APIDOC ## substring(int start, int end) ### Description Returns a new `Text` instance that is a substring of this Text, starting from the specified index and ending at the specified index. This method does not modify the original instance. ### Method `public CommandLine.Help.Ansi.Text substring(int start, int end)` ### Parameters #### Path Parameters - **start** (int) - The index in the plain text where to start the substring. - **end** (int) - The index in the plain text where to end the substring. ### Returns - **Text** - A new `Text` instance that is a substring of this `Text`. ``` -------------------------------- ### picocli.CommandLine.RunAll.handleParseResult Source: https://picocli.info/apidocs-all/index-files/index-8.html Prints help if requested, and otherwise executes the top-level command and all subcommands as Runnable, Callable or Method. ```APIDOC ## handleParseResult(List, PrintStream, CommandLine.Help.Ansi) ### Description Prints help if requested, and otherwise executes the top-level command and all subcommands as `Runnable`, `Callable` or `Method`. ### Method N/A (Method signature) ### Endpoint N/A ### Parameters - **List** (List) - A list of command line objects. - **PrintStream** (PrintStream) - The stream to print messages to. - **Ansi** (CommandLine.Help.Ansi) - Ansi settings for output formatting. ### Request Example N/A ### Response N/A (Executes commands) ``` -------------------------------- ### Get Default Arity Range for a Type (Deprecated) Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Range.html Deprecated method to get the default arity Range for options: booleans have arity 0, other types have arity 1. Use defaultArity(Field) instead. ```Java @Deprecated public static CommandLine.Range defaultArity(Class type) ``` -------------------------------- ### Example of Invalid User Input and Error Message Source: https://picocli.info/index.html This example shows the output when a user provides an invalid argument to a command. It includes the error message, valid argument suggestions, and the command's usage synopsis. ```text $ grep -d recurese "ERROR" logs/* Error: invalid argument ‘recurese’ for ‘--directories’ Valid arguments are: - ‘read’ - ‘recurse’ - ‘skip’ Usage: grep [OPTION]... PATTERN [FILE]... Try 'grep --help' for more information. ``` -------------------------------- ### CommandLine Configuration Methods Source: https://picocli.info/apidocs-all/info.picocli/picocli/class-use/CommandLine.html These methods allow configuration of how picocli displays usage help and handles argument files. ```APIDOC ## CommandLine.setUsageHelpAutoWidth ### Description Sets whether picocli should attempt to detect the terminal size and adjust the usage help message width to take the full terminal width. ### Method `setUsageHelpAutoWidth​(boolean detectTerminalSize)` ### Endpoint N/A (SDK Method) ### Parameters * **detectTerminalSize** (boolean) - Description: Whether to auto-detect terminal width. ``` ```APIDOC ## CommandLine.setUsageHelpLongOptionsMaxWidth ### Description Returns the maximum usage help long options column max width to the specified value. ### Method `setUsageHelpLongOptionsMaxWidth​(int columnWidth)` ### Endpoint N/A (SDK Method) ### Parameters * **columnWidth** (int) - Description: The maximum width for the long options column. ``` ```APIDOC ## CommandLine.setUsageHelpWidth ### Description Sets the maximum width of the usage help message. ### Method `setUsageHelpWidth​(int width)` ### Endpoint N/A (SDK Method) ### Parameters * **width** (int) - Description: The maximum width for the usage help message. ``` ```APIDOC ## CommandLine.setUseSimplifiedAtFiles ### Description Sets whether to use a simplified argument file format that is compatible with JCommander. ### Method `setUseSimplifiedAtFiles​(boolean simplifiedAtFiles)` ### Endpoint N/A (SDK Method) ### Parameters * **simplifiedAtFiles** (boolean) - Description: Whether to use the simplified argument file format. ``` -------------------------------- ### Generate Proxy Configuration for a Class Source: https://picocli.info/man/gen-proxy-config.html This example shows how to run the gen-proxy-config tool to generate a proxy configuration for a specific class. Ensure all necessary JARs, including picocli-core and picocli-codegen, are in the classpath. ```bash java -cp "myapp.jar;picocli-4.7.7.jar;picocli-codegen-4.7.7.jar" picocli.codegen.aot.graalvm.DynamicProxyConfigGenerator my.pkg.MyClass ``` -------------------------------- ### CommandLine.Range.min Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Range.html Gets the inclusive lower bound of the range. ```APIDOC ## CommandLine.Range.min ### Description Returns the lower bound of this range (inclusive). ### Method public int min() ### Returns - int: The lower bound of the range. ``` -------------------------------- ### CommandLine.Help.Layout.addAllOptions Source: https://picocli.info/apidocs-all/info.picocli/picocli/class-use/CommandLine.Model.OptionSpec.html Adds all options from a list to the layout. ```APIDOC ## addAllOptions ### Description Calls `CommandLine.Help.Layout.addOption(CommandLine.Model.OptionSpec, CommandLine.Help.IParamLabelRenderer)` for all Options in the specified list. ### Method `void` ### Parameters * **options** (List) - The list of option specifications to add. * **paramLabelRenderer** (CommandLine.Help.IParamLabelRenderer) - Renderer for parameter labels. ``` -------------------------------- ### Get Getter Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Model.IAnnotatedElement.html Returns the getter for the annotated element. ```java CommandLine.Model.IGetter getter() ``` -------------------------------- ### Get Name Source: https://picocli.info/apidocs-all/info.picocli/picocli/CommandLine.Model.IAnnotatedElement.html Returns the name of the annotated element. ```java String getName() ```