Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Different sample applications for manual and quick guide (#1171) #1173

Merged
merged 1 commit into from
Sep 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions docs/index.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
:toc: left
:numbered:
:toclevels: 2
:toc-title: Table of contents
:toc-title: Features
:source-highlighter: coderay
//:source-highlighter: highlightjs
//:highlightjs-theme: darkula
Expand Down Expand Up @@ -35,11 +35,11 @@ image:logo/horizontal.png[picocli the Mighty Tiny Command Line Interface,width=8
The user manual for the latest release is at http://picocli.info.
For the busy and impatient: there is also a link:quick-guide.html[Quick Guide].

== Introducing Picocli
== Introduction
Picocli is a one-file framework for creating Java command line applications with almost zero code.
Picocli aims to be the easiest way to create rich command line applications that can run on and off the JVM.

=== Features
=== Overview
Picocli supports a variety of command line syntax styles including POSIX, GNU, MS-DOS and more and generates highly customizable usage help messages with <<ANSI Colors and Styles,ANSI colors and styles>>.
Picocli-based applications can have link:autocomplete.html[command line TAB completion] showing available options, option parameters and subcommands, for any level of nested subcommands.
Picocli-based applications can be ahead-of-time compiled to a image:https://www.graalvm.org/resources/img/logo-colored.svg[GraalVM]
Expand All @@ -51,6 +51,8 @@ Another distinguishing feature of picocli is how it aims
to let users run picocli-based applications without requiring picocli as an external dependency:
all the source code lives in a single file, to encourage application authors to include it _in source form_.

This is how it works: you annotate your class and picocli initializes it from the command line arguments, converting the input to strongly typed values in the fields of your class. If your class implements `Runnable` or `Callable`, you can let picocli kick off your application after parsing is successfully completed.

=== Sample application
Let's get started by looking at minimal picocli-based command line application. This fully working sample app may be used to calculate the checksum(s) of one or more file(s) given as command line parameter(s):

Expand All @@ -72,25 +74,25 @@ import java.nio.file.Files;
import java.security.MessageDigest;
import java.util.concurrent.Callable;

@Command(name = "checksum", mixinStandardHelpOptions = true, version = "checksum 4.0", // <8>
@Command(name = "checksum", mixinStandardHelpOptions = true, version = "checksum 4.0",
description = "Prints the checksum (MD5 by default) of a file to STDOUT.")
class CheckSum implements Callable<Integer> { // <1>
class CheckSum implements Callable<Integer> {

@Parameters(index = "0", description = "The file whose checksum to calculate.") // <2>
@Parameters(index = "0", description = "The file whose checksum to calculate.")
private File file; // <4>

@Option(names = {"-a", "--algorithm"}, description = "MD5, SHA-1, SHA-256, ...") // <3>
private String algorithm = "MD5"; // <4>
@Option(names = {"-a", "--algorithm"}, description = "MD5, SHA-1, SHA-256, ...")
private String algorithm = "MD5";

// this example 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); // <5>
System.exit(exitCode); // <7>
int exitCode = new CommandLine(new CheckSum()).execute(args);
System.exit(exitCode);
}

@Override
public Integer call() throws Exception { // your business logic // <6>
public Integer call() throws Exception { // your business logic
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));
Expand All @@ -99,7 +101,9 @@ class CheckSum implements Callable<Integer> { // <1>
}
----

_This is how it works_: Create a class ➊ that represents your command and annotate this class with @Command ➑. Let this class implement `Runnable` or `Callable` and picocli will kick off your application after parsing is successfully completed. Then, annotate the fields or methods of the command class with @Parameters ➋ and/or @Option ➌ to declare what positional parameters and/or options your application expects. Picocli will convert the command line arguments given to your app to strongly typed values in the fields ➍ of your class. In the `main` method of your class, use the `CommandLine.execute` method ➎ to parse the command line, handle errors, handle requests for usage and version help, and invoke the business logic ➏. Once your business logic finished, you may call `System.exit` ➐ to return an exit code to your caller, indicating success or failure of your business logic. Additionally, you may make use of the <<Mixin Standard Help Options,mixinStandardHelpOptions>> attribute ➑ which adds `--help` and `--version` options to your application.
Create a class that represents your command and annotate this class with `@Command`. Let this class implement `Runnable` or `Callable` and your command can be <<Executing Commands,executed>> in one line of code. Annotate the fields of the command class with `@Option` or `@Parameters` to declare the options and positional parameters of your application. Use the `CommandLine.execute` method to parse the command line, handle errors, handle requests for usage and version help, and invoke the business logic. Eventually, your application may call `System.exit` with the returned exit code to signal success or failure to their caller.

The <<Mixin Standard Help Options,mixinStandardHelpOptions>> attribute adds --help and --version options to your application.

TIP: Picocli also provides a <<Programmatic API,programmatic API>>, separately from the annotations API.

Expand Down
74 changes: 50 additions & 24 deletions docs/quick-guide.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -28,44 +28,70 @@ Picocli-based applications can have link:autocomplete.html[command line TAB comp
.Example usage help message
image:ExampleUsageANSI.png[Screenshot of usage help with Ansi codes enabled]

== How to Use it
Create a class that represents your command and annotate this class with `@Command`. Then, annotate the fields or methods of the command class with `@Option` or `@Parameters` to declare what options and positional parameters your application expects. While parsing the command line, picocli will initialize these fields based on the command line arguments.
If your class implements `Runnable` or `Callable`, you can let picocli kick off your application after parsing is successfully completed.
== Sample application
Let’s get started by looking at minimal picocli-based command line application. This fully working sample app converts one or more words given as command line arguments into ASCII art and prints them out:

NOTE: For applications that cannot use the annotations, there is also a link:picocli-3.0-programmatic-api.html[programmatic API] for defining what options and positional parameters to expect, and a programmatic API for handling parse results. The programmatic API is not covered in this Quick Guide.
.Invoking the command
----
$ ASCIIArt --font=speed Picocli is great
_____________ __________ _____ _____
___ __ \__(_)____________________ /__(_) ___(_)_______ _______ __________________ __ /_
__ /_/ /_ /_ ___/ __ \ ___/_ /__ / __ /__ ___/ __ __ `/_ ___/ _ \ __ `/ __/
_ ____/_ / / /__ / /_/ / /__ _ / _ / _ / _(__ ) _ /_/ /_ / / __/ /_/ // /_
/_/ /_/ \___/ \____/\___/ /_/ /_/ /_/ /____/ _\__, / /_/ \___/\__,_/ \__/
/____/
----

=== Example
Here is a small example application that performs parsing and error handling in one line of code, leveraging the <<Executing Commands,execute API>> which was newly introduced with `picocli 4.0`. The <<Mixin Standard Help Options,mixinStandardHelpOptions>> attribute adds usage help and version help options your application.
.Synopsis of command
----
$ ASCIIArt --help
Usage: ASCIIArt [-hV] [-f=<font>] [word1 [word2]...]
[word1 [word2]...] Words to be translated into ASCII art.
-f, --font=<font> Font list: https://artii.herokuapp.com/fonts_list
-h, --help Show this help message and exit.
-V, --version Print version information and exit.
----

.Picocli-based example command line application
[[CheckSum-application]]
.Source Code
[source,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<Integer> {
@Command(name = "ASCIIArt", mixinStandardHelpOptions = true) // <8>
public class ASCIIArt implements Callable<Integer> { // <1>

@Parameters(index = "0", description = "The file whose checksum to calculate.")
private File file;
@Parameters(paramLabel = "word1 [word2]", description = "Words to be translated into ASCII art.") // <2>
private String[] words = { "Hello,", "world!" }; // <4>

@Option(names = {"-a", "--algorithm"}, description = "MD5, SHA-1, SHA-256, ...")
private String algorithm = "SHA-1";

public static void main(String... args) throws Exception {
int exitCode = new CommandLine(new CheckSum()).execute(args);
System.exit(exitCode);
}
@Option(names = { "-f", "--font" }, description = "Font list: https://artii.herokuapp.com/fonts_list") // <3>
String font = "standard"; // <4>

@Override
public Integer 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));
public Integer call() { // your business logic <6>
String text = String.join("+", words);
String URL = String.format("http://artii.herokuapp.com/make?text=%s&font=%s", text, font);

try (java.util.Scanner s = new java.util.Scanner(new java.net.URL(URL).openStream())) {
System.out.println(s.useDelimiter("\\A").next());
} catch (Exception e) {
System.err.println("Invalid font or invalid text given!");
return 1;
}
return 0;
}

public static void main(String[] args) {
int exitCode = new CommandLine(new ASCIIArt()).execute(args); // <5>
System.exit(exitCode); // <7>
}
}
----

_How to get started quickly_: Create a class ➊ that represents your command and annotate this class with @Command ➑. Let this class implement `Runnable` or `Callable` and picocli will kick off your application after parsing is successfully completed. Then, annotate the fields or methods of the command class with @Parameters ➋ and/or @Option ➌ to declare what positional parameters and/or options your application expects. Picocli will convert the command line arguments given to your app to strongly typed values in the fields ➍ of your class. In the `main` method of your class, use the `CommandLine.execute` method ➎ to parse the command line, handle errors, handle requests for usage and version help, and invoke the business logic ➏. Once your business logic finished, you may call `System.exit` ➐ to return an exit code to your caller, indicating success or failure of your business logic. Additionally, you may make use of the <<Mixin Standard Help Options,mixinStandardHelpOptions>> attribute ➑ which adds `--help` and `--version` options to your application.




NOTE: For applications that cannot use the annotations, there is also a link:picocli-programmatic-api.html[programmatic API] for defining what options and positional parameters to expect, and a programmatic API for handling parse results. The programmatic API is not covered in this Quick Guide.

== Options and Parameters
Command line arguments can be separated into _options_ and _positional parameters_.
Options have a name, positional parameters are usually the values that follow the options,
Expand Down
37 changes: 16 additions & 21 deletions picocli-examples/src/main/java/picocli/examples/i18n/I18NDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,30 @@
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;

public class I18NDemo {
@Command(name = "ASCIIArtGenerator", mixinStandardHelpOptions = true,
resourceBundle = "picocli.examples.i18n.Messages", version = "4.5.1")
public class I18NDemo implements Runnable {

@Command(name = "ASCIIArtGenerator", mixinStandardHelpOptions = true,
resourceBundle = "picocli.examples.i18n.Messages", version= "4.1.4")
static class ASCIIArtCommand implements Runnable {
@Parameters(paramLabel = "<word1> [<word2>]", arity = "0..*", descriptionKey = "words")
private String[] words = { "Hello,", "world!" };

@Parameters(paramLabel = "<word1> [<word2>]", arity = "0..*",
descriptionKey = "words")
private String[] words = { "Hello,", "world!"};
@Option(names = { "-f", "--font" }, descriptionKey = "font")
String font = "standard";

@Option(names = { "-f", "--font" }, descriptionKey = "font")
String font = "standard";
public void run() {
String text = String.join("+", words);
String URL = String.format("http://artii.herokuapp.com/make?text=%s&font=%s", text, font);

public void run() {
String text = String.join("+", words);
String URL = String.format("http://artii.herokuapp.com/make?text=%s&font=%s", text, font);

try (java.util.Scanner s = new java.util.Scanner(new java.net.URL(URL).openStream())) {
System.out.println(s.useDelimiter("\\A").next());
}
catch (Exception e) {
System.err.println("Invalid font or invalid text given!");
System.exit(1);
}
try (java.util.Scanner s = new java.util.Scanner(new java.net.URL(URL).openStream())) {
System.out.println(s.useDelimiter("\\A").next());
} catch (Exception e) {
System.err.println("Invalid font or invalid text given!");
System.exit(1);
}
}

public static void main(String[] args) {
CommandLine cmd = new CommandLine(new ASCIIArtCommand());
CommandLine cmd = new CommandLine(new I18NDemo());
cmd.execute(args);
}
}