### Java CLI with Picocli Source: https://github.com/remkop/picocli/blob/main/README.md A basic guide to creating command-line programs in Java using the Picocli library. Covers fundamental usage and setup for simple CLI tools. ```java import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; @Command(name = "hello", mixinStandardHelpOptions = true, version = "hello v1.0") class Hello implements Runnable { @Option(names = { "-g", "--greeting" }, defaultValue = "Hello", description = "The greeting") private String greeting; @Parameters(index = "0", description = "The target to greet.") private String target; @Override public void run() { System.out.println(greeting + " " + target + "!"); } public static void main(String[] args) { new CommandLine(new Hello()).execute(args); } } ``` -------------------------------- ### Command Line Help Usage Examples Source: https://github.com/remkop/picocli/blob/main/RELEASE-NOTES.md Provides examples of how to invoke the help functionality from the command line after integrating the `HelpCommand`. It shows how to get general help for the main command and specific help for a subcommand. ```text # print help for the `maincommand` command maincommand help # print help for the `subcommand` command maincommand help subcommand ``` -------------------------------- ### Basic Command-Line Application Structure in Java Source: https://github.com/remkop/picocli/blob/main/docs/man/generate-completion.html This snippet demonstrates the fundamental structure of a command-line application using the picocli library in Java. It includes setting up the main class, defining options and commands, and handling user input. This is a basic example for getting started with picocli. ```java import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; @Command(name = "myapp", version = "myapp 1.0", mixinStandardHelpOptions = true) public class MyApp implements Runnable { @Option(names = {"-v", "--verbose"}, description = "Verbose mode") private boolean verbose; public static void main(String[] args) { int exitCode = new CommandLine(new MyApp()).execute(args); System.exit(exitCode); } @Override public void run() { if (verbose) { System.out.println("Hello, world!"); } else { System.out.println("Hello, world! (use -v for verbose output)"); } } } ``` -------------------------------- ### Quarkus Command Mode with Picocli Source: https://github.com/remkop/picocli/blob/main/README.md Guide on setting up and using Quarkus' command mode with Picocli for building command-line tools. Covers integration and execution within the Quarkus ecosystem. ```java import io.quarkus.picocli.runtime.annotations.TopCommand; import picocli.CommandLine; @TopCommand public class CliApp implements Runnable { @Override public void run() { System.out.println("Hello Quarkus!"); } public static void main(String[] args) { new CommandLine(new CliApp()).execute(args); } } ``` -------------------------------- ### Scala CLI Tools with Picocli and GraalVM Source: https://github.com/remkop/picocli/blob/main/README.md Guides on building command-line tools using Scala, integrated with Picocli for parsing arguments, and compiled to native images with GraalVM. ```scala import picocli.CommandLine import picocli.CommandLine.{Command, Option, Parameters} import scala.annotation.meta.field @Command(name = "scalacli", mixinStandardHelpOptions = true) class ScalaCli extends Runnable { @Option(names = Array("-n", "--name"), description = Array("Name to greet")) private var name: String = "World" override def run(): Unit = { println(s"Hello, $name!") } } object ScalaCli { def main(args: Array[String]): Unit = { new CommandLine(new ScalaCli()).execute(args: _*) } } ``` -------------------------------- ### Full-Fledged Picocli Application Example (Java) Source: https://github.com/remkop/picocli/blob/main/docs/quick-guide.adoc A concise, 15-line Java application demonstrating a full-fledged command-line interface using Picocli. It includes standard help options (`--help`, `--version`), a custom option (`-x`), and business logic. ```java @Command(name = "myapp", mixinStandardHelpOptions = true, version = "1.0") class MyApp implements Callable { @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 Line Invocation Example Source: https://github.com/remkop/picocli/blob/main/docs/quick-guide.adoc Demonstrates how a command with subcommands might be invoked from the command line, including global options and subcommand options. Assumes an alias 'git' is set up. ```bash alias git='java picocli.Demo$Git' git --git-dir=/home/rpopma/picocli status -sb -uno ``` -------------------------------- ### Parse Command Line with Subcommands Source: https://github.com/remkop/picocli/blob/main/docs/quick-guide.adoc Example of setting up and invoking the `parse` method on a `CommandLine` instance to process arguments, including global options and subcommand-specific options. ```java public static void main(String... args) { // Set up the parser 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()) .addSubcommand("commit", new GitCommit()); ... // Invoke the parse method to parse the arguments ``` -------------------------------- ### Picocli Options and Parameters Example (Java) Source: https://github.com/remkop/picocli/blob/main/docs/quick-guide.adoc This Java code defines a `Tar` class using picocli annotations to parse command-line arguments. It showcases how to define options with single or multiple names, options that take parameters (like file paths), and positional parameters for input files. It also includes an example of parsing arguments and asserting the parsed values. ```java class Tar { @Option(names = "-c", description = "create a new archive") boolean create; @Option(names = { "-f", "--file" }, paramLabel = "ARCHIVE", description = "the archive file") File archive; @Parameters(paramLabel = "FILE", description = "one or more files to archive") File[] files; @Option(names = { "-h", "--help" }, usageHelp = true, description = "display a help message") private boolean helpRequested; } // Example of parsing arguments: String[] args = { "-c", "--file", "result.tar", "file1.txt", "file2.txt" }; Tar tar = new Tar(); new CommandLine(tar).parseArgs(args); // Assertions to verify parsing: // 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")}); ``` -------------------------------- ### Picocli Clustered Short Options (Java) Source: https://github.com/remkop/picocli/blob/main/docs/quick-guide.adoc This example demonstrates how picocli supports POSIX-style clustered short options. It shows equivalent command-line invocations for the `Tar` example, where multiple short options are grouped behind a single dash. This can simplify command-line usage for users. ```java // For the Tar example above, the following command line invocations are equivalent: // tar -c -f result.tar f1.txt f2.txt // tar -cf result.tar f1.txt f2.txt // tar -cfresult.tar f1.txt f2.txt ``` -------------------------------- ### Add Groovy, Kotlin, and Scala Examples Source: https://github.com/remkop/picocli/blob/main/RELEASE-NOTES.md This documentation improvement adds code examples in Groovy, Kotlin, and Scala to the user manual and quick guide. This expands the language support and makes the documentation more accessible to a wider audience. ```groovy #1255 DOC: User manual and Quick Guide: add Groovy, Kotlin and Scala examples. ``` ```kotlin #1255 DOC: User manual and Quick Guide: add Groovy, Kotlin and Scala examples. ``` ```scala #1255 DOC: User manual and Quick Guide: add Groovy, Kotlin and Scala examples. ``` -------------------------------- ### Add System Properties Example to User Manual Source: https://github.com/remkop/picocli/blob/main/RELEASE-NOTES.md This documentation update introduces an example demonstrating the use of system properties within the user manual. It aims to clarify how system properties can be leveraged with Picocli. ```java #1234 DOC: add system properties example to user manual. ``` -------------------------------- ### Basic Picocli Application Skeleton Source: https://github.com/remkop/picocli/blob/main/docs/quick-guide.adoc This snippet illustrates the essential structure for a picocli application. It includes setup for command parsing, error handling, help messages, and invoking business logic via the `CommandLine.execute` method. The exit code is used to signal success or failure. ```java import picocli.CommandLine; public class MyApp { public static void main(String[] args) { int exitCode = new CommandLine(new MyApp()).execute(args); System.exit(exitCode); } } ``` -------------------------------- ### Bash Command Execution Example Source: https://github.com/remkop/picocli/blob/main/README.md Illustrates how to execute the Java Example class with command-line arguments. It shows the verbose output generated when the -v option is provided. ```bash java Example -v inputFile1 inputFile2 2 files to process... ``` -------------------------------- ### Picocli Application with Subcommands and Help Source: https://github.com/remkop/picocli/blob/main/docs/quick-guide.adoc This Java code demonstrates a basic picocli application structure with subcommands. It includes a 'help' subcommand that automatically generates usage messages. The example highlights how picocli handles command-line argument parsing and subcommand routing. ```java class ISOCodeResolver { // ... (subcommand definitions and main method) } // Usage help message of our `ISOCodeResolver` command // $ ISOCodeResolver help // Usage: ISOCodeResolver [COMMAND] // Resolves ISO country codes (ISO-3166-1) or language codes (ISO-639-1/-2) // Commands: // help Display help information about the specified command. // country Resolves ISO country codes (ISO-3166-1) // language Resolves one or more ISO language codes (ISO-639-1 or 639-2) ``` -------------------------------- ### Basic ASCIIArt Java Application Example Source: https://github.com/remkop/picocli/blob/main/docs/quick-guide.adoc Demonstrates a simple picocli application named 'ASCIIArt' that converts words into ASCII art. It utilizes the annotation API for defining options and parameters, and implements the Runnable interface for command logic. The example includes standard help options. ```java import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; // some exports omitted for the sake of brevity @Command(name = "ASCIIArt", version = "ASCIIArt 1.0", mixinStandardHelpOptions = true) // <2> public class ASCIIArt implements Runnable { // <1> @Option(names = { "-s", "--font-size" }, description = "Font size") // <3> int fontSize = 19; @Parameters(paramLabel = "", defaultValue = "Hello, picocli", // <4> description = "Words to be translated into ASCII art.") private String[] words = { "Hello,", "picocli" }; // <5> @Override public void run() { // <6> // The business logic of the command goes here... // In this case, code for generation of ASCII art graphics // (omitted for the sake of brevity). } public static void main(String[] args) { int exitCode = new CommandLine(new ASCIIArt()).execute(args); // <7> System.exit(exitCode); // <8> } } ``` -------------------------------- ### Enable Picocli Tracing with a Bash Alias Source: https://github.com/remkop/picocli/blob/main/docs/quick-guide.adoc This example demonstrates how to create a Bash alias to run a Picocli application with tracing enabled via a system property. It specifies the Java classpath and the main class to execute, along with sample command-line arguments. ```bash alias mygit='java -Dpicocli.trace -cp picocli-all.jar picocli.Demo$Git' # invoke our command with some parameters mygit --git-dir=/home/rpopma/picocli commit -m "Fixed typos" -- src1.java src2.java src3.java ``` -------------------------------- ### Improve example code in picocli-spring-boot-starter README (Markdown) Source: https://github.com/remkop/picocli/blob/main/RELEASE-NOTES.md Enhances the example code provided in the README file for the `picocli-spring-boot-starter`. This update aims to provide clearer and more effective examples for users. ```markdown (DOC) Improve example code in `picocli-spring-boot-starter` README. Thanks to [Stéphane Nicoll](https://github.com/snicoll) for the pull requests. ``` -------------------------------- ### Documentation: Update Examples for New Execute API Source: https://github.com/remkop/picocli/blob/main/RELEASE-NOTES.md Updates documentation examples to reflect the usage of the new `execute` API, including demonstrations for exit code control and custom exception handlers. ```APIDOC ## Documentation: Update Examples for New Execute API ### Description Provides updated examples demonstrating the new `execute` API, covering exit code management and custom exception handling. ### Method N/A (This describes documentation updates) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Related Issue [#679] ``` -------------------------------- ### Picocli: Example Usage for Help (Java) Source: https://github.com/remkop/picocli/blob/main/docs/man/1.x/index.html Shows a basic example of how to generate usage help for a Picocli application using `CommandLine.usage`. This is often used in conjunction with custom layouts or subcommand structures. ```java CommandLine.usage(new ZipHelpDemo(), System.out); ``` -------------------------------- ### Example Usage of IExtensible (Java) Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/info.picocli/picocli/CommandLine.Model.IExtensible.html Demonstrates how to check if an IAnnotatedElement is IExtensible and retrieve an extension. This example shows casting to IExtensible and using getExtension to get an InitialValueState. ```java // suppose we want to add a method `getInitialValueState` to `IAnnotatedElement` IAnnotatedElement element = getAnnotatedElement(); if (element instanceof IExtensible) { InitialValueState state = ((IExtensible) element).getExtension(InitialValueState.class); if (state != null) { // ... } } ``` -------------------------------- ### Picocli: Get Text Substring (Start Index) Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/index-files/index-19.html Returns a new `Text` instance representing a substring of the original `Text`, starting from the specified index. This method is in `CommandLine.Help.Ansi.Text`. ```Java substring(int) ``` -------------------------------- ### Building Native Java CLIs with GraalVM, Picocli, and Gradle Source: https://github.com/remkop/picocli/blob/main/README.md Walkthrough on creating native executable command-line applications in Java using Picocli for argument parsing and GraalVM with Gradle for native compilation. ```gradle plugins { id 'java' id 'application' id 'org.graalvm.sdk' } repositories { mavenCentral() } dependencies { implementation 'info.picocli:picocli:4.6.2' } application { mainClassName 'com.example.MyCliApp' } graalvmNativeImage { executableName = 'mycli' } ``` -------------------------------- ### Picocli: Get Text Substring (Start and End Index) Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/index-files/index-19.html Returns a new `Text` instance that is a substring of the original `Text`, defined by the start and end indices. This method is part of `CommandLine.Help.Ansi.Text`. ```Java substring(int, int) ``` -------------------------------- ### Automatic Help Demo in Java Source: https://github.com/remkop/picocli/blob/main/docs/picocli-2.0-do-more-with-less.adoc Demonstrates how Picocli automatically handles usage and version help requests via annotated options. It shows a simple command-line application that prints 'Hello world' and includes options for help and version information. ```java @Command(version = "Help demo v1.2.3", header = "%nAutomatic Help Demo%n", description = "Prints usage help and version help when requested.%n") class AutomaticHelpDemo implements Runnable { @Option(names = "--count", description = "The number of times to repeat.") int count; @Option(names = {"-h", "--help"}, usageHelp = true, description = "Print usage help and exit.") boolean usageHelpRequested; @Option(names = {"-V", "--version"}, versionHelp = true, description = "Print version information and exit.") boolean versionHelpRequested; public void run() { // NOTE: code like below is no longer required: // // if (usageHelpRequested) { // new CommandLine(this).usage(System.err); // } else if (versionHelpRequested) { // new CommandLine(this).printVersionHelp(System.err); // } else { ... the business logic for (int i = 0; i < count; i++) { System.out.println("Hello world"); } } public static void main(String... args) { CommandLine.run(new AutomaticHelpDemo(), System.err, args); } } ``` -------------------------------- ### Install Short Error Message Handler - Picocli Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/picocli/CommandLine.html Example of installing a custom `ShortErrorMessageHandler` to provide concise error messages for invalid user input. This handler prints the error message, suggestions, and a usage hint. ```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(); } } new CommandLine(new MyApp()) .setParameterExceptionHandler(new ShortErrorMessageHandler()) ``` -------------------------------- ### Create a Starter Script for a Picocli Application Source: https://github.com/remkop/picocli/blob/main/docs/A-Whirlwind-Tour-of-Picocli.adoc Provides an example of a bash starter script for a Java Picocli application. This script sets the classpath and invokes the main class, allowing it to be called like a regular command. ```bash #!/usr/bin/env bash LIBS=/home/user/me/libs CP="${LIBS}/checksum.jar:${LIBS}/picocli-3.9.5.jar" java -cp "${CP}" 'picocli.example.CheckSum' $@ ``` -------------------------------- ### Get substring of Text with start and end indices (Java) Source: https://github.com/remkop/picocli/blob/main/docs/man/2.x/apidocs/picocli/CommandLine.Help.Ansi.Text.html Returns a new Text instance that is a substring of the current Text object, defined by start and end indices. The original Text object remains unchanged by this operation. ```Java public CommandLine.Help.Ansi.Text substring(int start, int end) { // Returns a new Text instance that is a substring of this Text. Does not modify this instance! // Parameters: start - index in the plain text where to start the substring // end - index in the plain text where to end the substring // Returns: a new Text instance that is a substring of this Text } ``` -------------------------------- ### Shared Resource Bundles Example Source: https://github.com/remkop/picocli/blob/main/docs/index.adoc Illustrates organizing resource keys in a shared bundle, including command-specific prefixes like `jfrog.rt.` and general keys like `usage.footerHeading`. ```properties # shared between all commands usage.footerHeading = Environment Variables: usage.footer.0 = footer line 0 usage.footer.1 = footer line 1 ``` -------------------------------- ### Example Resource Bundle Configuration (Properties) Source: https://github.com/remkop/picocli/blob/main/docs/man/3.x/index.html This section shows an example of a properties file used as a resource bundle for customizing the help messages of a Picocli application. It includes keys for headers, descriptions, synopsis, and footer, demonstrating multi-line support. ```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. help = Show this help message and exit. version = Print version information and exit. # For @Option(names = {"-v", "--verbose) boolean[] verbose; verbose = Show more detail during execution. \ May be specified multiple times for increasing verbosity. # For @Parameters(paramLabel="FILES") File[]; FILES[0..*] = The files to process. ``` -------------------------------- ### Picocli Subcommands Example Source: https://github.com/remkop/picocli/blob/main/docs/man/1.x/autocomplete.html Shows how to structure a Picocli application with multiple subcommands. This example defines a main command with 'add' and 'list' subcommands. ```java import picocli.CommandLine; import picocli.CommandLine.Command; @Command(name = "myapp", mixinStandardHelpOptions = true, version = "myapp 1.0", subcommands = { AddCommand.class, ListCommand.class }) public class MyApp { public static void main(String[] args) { int exitCode = new CommandLine(new MyApp()).execute(args); System.exit(exitCode); } } @Command(name = "add", version = "add 1.0", description = "Adds a new item") class AddCommand implements Runnable { @Override public void run() { System.out.println("Executing add command."); } } @Command(name = "list", version = "list 1.0", description = "Lists items") class ListCommand implements Runnable { @Override public void run() { System.out.println("Executing list command."); } } ``` -------------------------------- ### Get End-of-Options Delimiter Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/info.picocli/picocli/CommandLine.html Retrieves the delimiter that signals the end of options and the start of positional parameters. The default is '--'. ```APIDOC ## GET /api/commandline/end-of-options-delimiter ### Description Retrieves the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters. ### Method GET ### Endpoint /api/commandline/end-of-options-delimiter ### Parameters None ### Response #### Success Response (200) - **delimiter** (String) - The end-of-options delimiter. The default is "--". #### Response Example ```json { "delimiter": "--" } ``` ``` -------------------------------- ### Install Linux Compiler Toolchain Source: https://github.com/remkop/picocli/blob/main/docs/build-great-native-cli-apps-in-java-with-graalvm-and-picocli.adoc Installs necessary development packages on Linux for `native-image` compilation, including GCC, glibc-devel, and zlib-devel headers. ```bash sudo dnf install gcc glibc-devel zlib-devel ``` ```bash sudo apt-get install build-essential libz-dev ``` -------------------------------- ### Get Substring of Ansi.Text Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/info.picocli/picocli/CommandLine.Help.Ansi.Text.html Returns a new Ansi.Text instance that is a substring of this Text, starting from the specified index. ```java picocli.CommandLine.Help.Ansi.Text.substring(int start) ``` -------------------------------- ### Picocli Automatic Help Demonstration in Java Source: https://github.com/remkop/picocli/blob/main/docs/man/3.x/picocli-2.0-do-more-with-less.html Provides an example of a picocli application that automatically handles and displays usage help and version information when requested via command-line options. ```java @Command(version = "Help demo v1.2.3", header = "%nAutomatic Help Demo%n", description = "Prints usage help and version help when requested.%n") class AutomaticHelpDemo implements Runnable { @Option(names = "--count", description = "The number of times to repeat.") int count; @Option(names = {"-h", "--help"}, usageHelp = true, description = "Print usage help and exit.") boolean usageHelpRequested; @Option(names = {"-V", "--version"}, versionHelp = true, description = "Print version information and exit.") boolean versionHelpRequested; public void run() { // NOTE: code like below is no longer required: ``` -------------------------------- ### Improve Micronaut Example with Kotlin Version Source: https://github.com/remkop/picocli/blob/main/RELEASE-NOTES.md Enhances the user manual's Micronaut example by adding a Kotlin version and an extended description of Micronaut usage. This aims to provide a more comprehensive guide for users integrating Picocli with Micronaut using Kotlin. ```kotlin #1232 DOC: User manual improvements for Micronaut example: add Kotlin version, extended description of Micronaut usage. ``` -------------------------------- ### CommandLine.IHelpFactory Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/info.picocli/picocli/CommandLine.IHelpFactory.html Interface for creating Help instances to render usage help messages. ```APIDOC ## GET /create ### Description This method creates a `Help` instance to assist in rendering the usage help message for a command. ### Method GET ### Endpoint /create ### Parameters #### Query Parameters - **commandSpec** (CommandLine.Model.CommandSpec) - Required - The command to create usage help for. - **colorScheme** (CommandLine.Help.ColorScheme) - Required - The color scheme to use when rendering usage help. ### Response #### Success Response (200) - **Help instance** (CommandLine.Help) - A Help instance used for rendering usage help. #### Response Example { "example": "// Returns a Help instance" } ``` -------------------------------- ### Picocli Options and Parameters Definition Source: https://github.com/remkop/picocli/blob/main/docs/man/3.x/quick-guide.html A Java example showcasing the definition of command-line options and parameters using picocli annotations. It includes examples of boolean flags, options with parameters, array parameters, and usage help options. ```Java class Tar { @Option(names = "-c", description = "create a new archive") boolean create; @Option(names = { "-f", "--file" }, paramLabel = "ARCHIVE", description = "the archive file") File archive; @Parameters(paramLabel = "FILE", description = "one or more files to archive") File[] files; @Option(names = { "-h", "--help" }, usageHelp = true, description = "display a help message") private boolean helpRequested; } ``` -------------------------------- ### Basic "Hello, World!" CLI with picocli Source: https://github.com/remkop/picocli/blob/main/docs/man/2.x/announcing-picocli-1.0.html A simple example demonstrating the fundamental structure of a picocli application. It showcases how to define a command and print a greeting message. Requires the picocli library. ```java import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; @Command(name = "hello", mixinStandardHelpOptions = true, version = "hello 0.0.1", description = "Prints a greeting.") class HelloWorld { @Option(names = {"-g", "--greeting"}, defaultValue = "Hello", description = "The greeting to use.") private String greeting; @Option(names = {"-n", "--name"}, required = true, description = "The name to greet.") private String name; public static void main(String[] args) { new CommandLine(new HelloWorld()).execute(args); } public void run() { System.out.printf("%s %s!%n", greeting, name); } } ``` -------------------------------- ### IHelpCommandInitializable Documentation Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/picocli/CommandLine.IHelpCommandInitializable.html Provides details on initializing a help command with streams and ANSI color support. ```APIDOC ## Class CommandLine.IHelpCommandInitializable ### Description This interface is used to initialize a help command, providing it with the necessary information to generate usage help for other commands. It allows configuration of output streams and ANSI color usage. ### Method * `void initializeHelpCommand(CommandLine helpCommandLine, boolean ansi, PrintStream out, PrintStream err)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) This is a documentation interface, not an API endpoint. Methods within implementing classes would handle responses. #### Response Example None ### Deprecated This method is deprecated. Consider using newer alternatives if available. ``` -------------------------------- ### ArgSpec Description Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/deprecated-list.html Details on how to get the rendered description of an argument specification. It suggests using `CommandLine.Model.ArgSpec.description()` for direct access to the description. ```APIDOC ## CommandLine.Model.ArgSpec.renderedDescription() ### Description Returns the rendered description of an argument specification, potentially including formatting. ### Method GET ### Endpoint /argSpec/renderedDescription ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **description** (String) - The formatted description of the argument. #### Response Example ```json { "description": "This is a required input file." } ``` ``` -------------------------------- ### Picocli 'import' command examples Source: https://github.com/remkop/picocli/blob/main/picocli-codegen/src/test/resources/import.manpage.txt.adoc This section provides practical examples of how to use the 'import' command for different scenarios. It demonstrates importing data from CSV files into specific tables with various column mappings. ```bash # This imports all rows from the IP_Allocation_v1.20.csv file into the `null` table. import -v src/test/resources/IP_Allocation_v1.20.csv -Chostname=hostname -Chw_type=server_type -Cenv=class -Cdeviceid=null -Cenv=env -Cteam=team -COS=os -Cremarks=description -Crack=rack -Clocation=datacenter -Cmgmt_ip=management_ip -Cfront_ip=front_ip -Cilo_ip=ilo_ip -Capp=application ``` ```bash # This imports all rows from the network.csv file into the `network` table. import -v --table=network src/test/resources/network.csv -Cdesc=purpose -CDC=datacenter -Csubnet=subnet -Cgateway=gateway -Cvlanid=network ``` -------------------------------- ### Picocli: Execute Command and Get Result Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/deprecated-list.html Illustrates the recommended approach for executing commands and retrieving their execution results, replacing the older 'invoke' methods. ```java CommandLine.execute(String...) CommandLine.getExecutionResult() ``` -------------------------------- ### Picocli IHelpFactory: Create Help Instances Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/allclasses-index.html The IHelpFactory interface is responsible for creating CommandLine.Help instances, which are used to render the usage help message for commands. It allows customization of the help message generation process. ```Java package picocli; import picocli.CommandLine.Help; import picocli.CommandLine.Model.CommandSpec; public interface IHelpFactory { Help create(CommandSpec commandSpec); } ``` -------------------------------- ### Get Substring of Ansi.Text with End Index Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/info.picocli/picocli/CommandLine.Help.Ansi.Text.html Returns a new Ansi.Text instance that is a substring of this Text, from the specified start index to the specified end index. ```java picocli.CommandLine.Help.Ansi.Text.substring(int start, int end) ``` -------------------------------- ### Initialize Help Command with Usage Information (Java) Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/picocli/CommandLine.IHelpCommandInitializable2.html The `init` method initializes a help command with the necessary details to display usage help. It takes the CommandLine instance, a ColorScheme, and PrintWriter instances for output and error streams. This is called by `CommandLine.printHelpIfRequested` before executing the help command. ```java void init(CommandLine helpCommandLine, CommandLine.Help.ColorScheme colorScheme, PrintWriter outWriter, PrintWriter errWriter) ``` -------------------------------- ### Create Default Layout (no args) Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/picocli/CommandLine.Help.html Returns a Layout instance configured with the user preferences captured in this Help instance. ```APIDOC ## GET /api/help/layout/default ### Description Returns a Layout instance configured with the user preferences captured in this Help instance. ### Method GET ### Endpoint /api/help/layout/default ``` -------------------------------- ### Picocli Callable Application Example Source: https://github.com/remkop/picocli/blob/main/docs/man/3.x/quick-guide.html A Java example demonstrating a picocli application that implements Callable. It uses @Command, @Parameters, and @Option annotations to define command-line arguments and includes a main method for parsing and executing the application. ```Java @Command(description = "Prints the checksum (MD5 by default) of a file to STDOUT.", name = "checksum", mixinStandardHelpOptions = true, version = "checksum 3.0") 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"; public static void main(String[] args) throws Exception { CommandLine.call(new CheckSum(), args); } @Override public Void call() throws Exception { byte[] fileContents = Files.readAllBytes(file.toPath()); byte[] digest = MessageDigest.getInstance(algorithm).digest(fileContents); System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(digest)); return null; } } ``` -------------------------------- ### Help Constructor Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/picocli/CommandLine.Help.html Constructs a new Help instance with the specified color scheme, initialized from annotations on the specified CommandSpec. ```APIDOC ## Help Constructor ### Description Constructs a new `Help` instance with the specified color scheme, initialized from annotations on the specified class and superclasses. ### Method `Help(CommandLine.Model.CommandSpec commandSpec, CommandLine.Help.ColorScheme colorScheme)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Example usage CommandLine.Model.CommandSpec commandSpec = CommandLine.getCommandSpec(myCommandClass); CommandLine.Help.ColorScheme colorScheme = new CommandLine.Help.ColorScheme.Builder().build(); Help help = new Help(commandSpec, colorScheme); ``` ### Response #### Success Response (N/A) This is a constructor. #### Response Example N/A ``` -------------------------------- ### Negatable Boolean Options in Picocli Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/picocli/CommandLine.Option.html Automatically adds a negative version for boolean options. For example, an option `--enable` would also get a `--disable` counterpart. ```Java /** * (Only for boolean options): set this to automatically add a negative version for this boolean option. */ @Option(names = "--feature", negatable = true) private boolean featureEnabled; ``` -------------------------------- ### Picocli: Get Usage and Version Help for Options Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/deprecated-list.html Explains how to retrieve usage and version-specific help information for command-line options, replacing the generic 'help()' method. ```java CommandLine.Model.OptionSpec.usageHelp() CommandLine.Model.OptionSpec.versionHelp() ``` -------------------------------- ### Create Default Layout (with args) Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/picocli/CommandLine.Help.html Returns a Layout instance configured with the user preferences, considering provided options, positional parameters, and a color scheme. ```APIDOC ## GET /api/help/layout/default-with-args ### Description Returns a Layout instance configured with the user preferences captured in this Help instance. ### Method GET ### Endpoint /api/help/layout/default-with-args #### Query Parameters - **options** (List) - Optional - A list of OptionSpec objects. - **positionals** (List) - Optional - A list of PositionalParamSpec objects. - **aColorScheme** (ColorScheme) - Optional - The color scheme to use for the layout. ``` -------------------------------- ### Persistently Install Autocompletion Scripts Source: https://github.com/remkop/picocli/blob/main/docs/A-Whirlwind-Tour-of-Picocli.adoc A bash command to find all `*_completion` files in the current directory and add them to `.bash_profile` without creating duplicates, ensuring permanent autocompletion setup. ```bash $ for f in $(find . -name "*_completion"); do line=". $(pwd)/$f"; grep "$line" ~/.bash_profile || echo "$line" >> ~/.bash_profile; done ``` -------------------------------- ### Programmatic API Example for Command Line App Source: https://github.com/remkop/picocli/blob/main/RELEASE-NOTES.md Demonstrates how to build a command-line application programmatically using Picocli's CommandSpec. This example includes standard help options, a count option, and positional parameters for files, handling parsed results. ```java CommandSpec spec = CommandSpec.create(); spec.mixinStandardHelpOptions(true); // usageHelp and versionHelp options spec.addOption(OptionSpec.builder("-c", "--count") .paramLabel("COUNT") .type(int.class) .description("number of times to execute").build()); spec.addPositional(PositionalParamSpec.builder() .paramLabel("FILES") .type(List.class) .auxiliaryTypes(File.class) // List .description("The files to process").build()); CommandLine commandLine = new CommandLine(spec); commandLine.parseWithSimpleHandlers(new AbstractSimpleParseResultHandler() { public void handle(ParseResult pr) { int count = pr.optionValue('c', 1); List files = pr.positionalValue(0, Collections.emptyList()); for (int i = 0; i < count; i++) { for (File f : files) { System.out.printf("%d: %s%n", i, f); } } } }, args); ``` -------------------------------- ### Get AtFile Comment Character - picocli Source: https://github.com/remkop/picocli/blob/main/docs/man/3.x/apidocs/index-all.html Retrieves the character that signifies the start of a single-line comment in argument files. Returns null if no comment character is defined and all content is treated as arguments. ```java /** * Returns the character that starts a single-line comment or `null` if all content of argument files should be interpreted as arguments (without comments). */ char getAtFileCommentChar(); ``` -------------------------------- ### Picocli Help API Source: https://github.com/remkop/picocli/blob/main/docs/apidocs/picocli/CommandLine.Help.html Provides documentation for the constructors and methods of the picocli.CommandLine.Help class. ```APIDOC ## Constructors ### `Help(CommandSpec commandSpec, Help.ColorScheme colorScheme)` **Description:** Constructs a new `Help` instance with the specified color scheme, initialized from annotations on the specified class and superclasses. **Parameters:** * **commandSpec** (CommandSpec) - Required - The command specification. * **colorScheme** (Help.ColorScheme) - Required - The color scheme to use for help messages. ### `Help(Object command)` **Description:** Constructs a new `Help` instance with a default color scheme, initialized from annotations on the specified class and superclasses. **Parameters:** * **command** (Object) - Required - The command object. ### `Help(Object command, Help.Ansi ansi)` **Description:** Constructs a new `Help` instance with a default color scheme, initialized from annotations on the specified class and superclasses. **Parameters:** * **command** (Object) - Required - The command object. * **ansi** (Help.Ansi) - Required - The ANSI escape sequence setting. ### `Help(Object command, Help.ColorScheme colorScheme)` (Deprecated) **Description:** Deprecated. Use `picocli.CommandLine.Help#Help(picocli.CommandLine.Model.CommandSpec, picocli.CommandLine.Help.ColorScheme)` instead. **Parameters:** * **command** (Object) - Required - The command object. * **colorScheme** (Help.ColorScheme) - Required - The color scheme to use for help messages. ## Methods ### `String abbreviatedSynopsis()` **Description:** Generates a generic synopsis like ` [OPTIONS] [PARAM1 [PARAM2]...]`, omitting parts that don't apply to the command (e.g., does not show `[OPTIONS]` if the command has no options). **Method:** GET **Endpoint:** N/A (Instance method) ### `Help addAllSubcommands(Map subcommands)` **Description:** Registers all specified subcommands with this Help instance. **Parameters:** * **subcommands** (Map) - Required - A map of subcommand names to `CommandLine` instances. **Returns:** `Help` - The current `Help` instance for chaining. **Method:** POST **Endpoint:** N/A (Instance method) ``` -------------------------------- ### Get AtFile Comment Character in Picocli Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/info.picocli/picocli/CommandLine.html Retrieves the character that signifies the start of a single-line comment in argument files. If no comment character is defined, all file content is treated as arguments. ```java Character getAtFileCommentChar() ``` -------------------------------- ### IHelpCommandInitializable2 Initialization Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/info.picocli/picocli/CommandLine.IHelpCommandInitializable2.html Initializes the help command with necessary components for displaying usage information. ```APIDOC ## Initializing Help Command ### Description Initializes this object with the information needed to implement a help command that provides usage help for other commands. ### Method (Implicitly a constructor or initialization method, not a standard HTTP method) ### Endpoint (Not applicable - this describes an interface initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "helpCommandLine": "CommandLine object for help command", "colorScheme": "ColorScheme object for colors", "outWriter": "Writer for output", "errWriter": "Writer for errors" } ``` ### Response #### Success Response (Initialization) (No explicit response, initialization is typically in-place) #### Response Example (Not applicable) ``` -------------------------------- ### Required Positional Parameter Declaration Source: https://github.com/remkop/picocli/blob/main/docs/quick-guide.adoc Demonstrates how to make positional parameters mandatory by specifying a range using the `arity` attribute. This example requires at least one File parameter. ```java @Parameters(arity = "1..*", description = "at least one File") List files; ``` -------------------------------- ### Initialize Help Command Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/info.picocli/picocli/CommandLine.IHelpCommandInitializable2.html Initializes a help command implementation with the command-line object, color scheme, and output writers. ```APIDOC ## void init(CommandLine helpCommandLine, CommandLine.Help.ColorScheme colorScheme, PrintWriter outWriter, PrintWriter errWriter) ### Description Initializes this object with the information needed to implement a help command that provides usage help for other commands. ### Method `void` ### Endpoint N/A (Interface Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (void) This method does not return a value. #### Response Example None ``` -------------------------------- ### Execute and exitProcess (Kotlin) Source: https://github.com/remkop/picocli/blob/main/docs/index.adoc This Kotlin snippet demonstrates the equivalent of the Java example, using `CommandLine.execute` to get an exit code and `exitProcess` to terminate the application with that code. ```kotlin fun main(args: Array) { val exitCode = CommandLine(MyApp()).execute(*args) exitProcess(exitCode) } ``` -------------------------------- ### Example Resource Bundle Properties (i18n) Source: https://github.com/remkop/picocli/blob/main/docs/index.adoc Provides an example of a Java properties resource bundle file used for internationalization in Picocli. It includes keys for usage help sections, option descriptions, and command attributes. ```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 ``` -------------------------------- ### Get Actual Generic Type Arguments (Java) Source: https://github.com/remkop/picocli/blob/main/docs/apidocs-all/info.picocli/picocli/CommandLine.Model.ITypeInfo.html Returns the names of the type arguments if this is a generic type. For example, returns ["java.lang.String"] if this type is List. ```java List getActualGenericTypeArguments() // Returns the names of the type arguments if this is a generic type. ``` -------------------------------- ### Picocli: Create IHelpFactory Instance Source: https://github.com/remkop/picocli/blob/main/docs/man/3.x/apidocs/index-all.html Method in interface picocli.CommandLine.IHelpFactory. Returns a Help instance to assist in rendering the usage help message. This allows customization of help output. ```java picocli.CommandLine.IHelpFactory.create(CommandLine.Model.CommandSpec, CommandLine.Help.ColorScheme) ```