Coder Social home page Coder Social logo

remkop / picocli Goto Github PK

View Code? Open in Web Editor NEW
4.7K 48.0 405.0 81.72 MB

Picocli is a modern framework for building powerful, user-friendly, GraalVM-enabled command line apps with ease. It supports colors, autocompletion, subcommands, and more. In 1 source file so apps can include as source & avoid adding a dependency. Written in Java, usable from Groovy, Kotlin, Scala, etc.

Home Page: https://picocli.info

License: Apache License 2.0

Java 95.83% Shell 1.86% Groovy 1.60% HTML 0.06% Kotlin 0.52% Scala 0.13%
java commandline parser ansi-colors annotations ansi subcommands cli cli-framework git

picocli's Introduction

picocli

GitHub Release Maven Central GitHub Actions Build Status Tests codecov Follow @remkopopma Follow @picocli Follow picocli on StackShare

picocli - a mighty tiny command line interface

Picocli aims to be the easiest-to-use way to create rich command line applications that can run on and off the JVM. Considering picocli? Check what happy users say about picocli.

Picocli is a modern library and framework, written in Java, that contains both an annotations API and a programmatic API. It features usage help with ANSI colors and styles, TAB autocompletion and nested subcommands. In a single file, so you can include it in source form. This lets users run picocli-based applications without requiring picocli as an external dependency.

Picocli-based applications can be ahead-of-time compiled to a GraalVM native image, with extremely fast startup time and lower memory requirements, which can be distributed as a single executable file. Picocli comes with an annotation processor that automatically Graal-enables your jar during compilation.

Picocli applications can be very compact with no boilerplate code: your command (or subcommand) can be executed with a single line of code. Simply implement Runnable or Callable, or put the business logic of your command in a @Command-annotated method.

Picocli Demo help message with ANSI colors

Picocli makes it easy to follow Command Line Interface Guidelines.

How it works: annotate your class and picocli initializes it from the command line arguments, converting the input to strongly typed data. Supports git-like subcommands (and nested sub-subcommands), any option prefix style, POSIX-style grouped short options, custom type converters, password options and more.

Picocli distinguishes between named options and positional parameters and allows both to be strongly typed. Multi-valued fields can specify an exact number of parameters or a range (e.g., 0..*, 1..2). Supports Map options like -Dkey1=val1 -Dkey2=val2, where both key and value can be strongly typed. Parser tracing facilitates troubleshooting. Command-line argument files (@-files) allow applications to handle very long command lines.

Generates polished and easily tailored usage help and version help, using ANSI colors where possible. Requires at minimum Java 5, but is designed to facilitate the use of Java 8 lambdas. Tested on all Java versions between 5 and 18-ea (inclusive).

Picocli-based command line applications can have TAB autocompletion, interactively showing users what options and subcommands are available. When an option has completionCandidates or has an enum type, autocompletion can also suggest option values. Picocli can generate completion scripts for bash and zsh, and offers picocli-shell-jline2 and picocli-shell-jline3 modules with JLine Completer implementations for building interactive shell applications.

Unique features in picocli include support for negatable options, advanced quoted values, and argument groups. Argument groups can be used to create mutually exclusive options, mutually dependent options, option sections in the usage help message and repeating composite arguments like ([-a=<a> -b=<b> -c=<c>] (-x | -y | -z)).... For advanced use cases, applications can access the picocli command object model with the @Spec annotation, and implement custom parameter processing for option parameters if the built-in logic is insufficient.

Picocli-based applications can easily integrate with Dependency Injection containers. The Micronaut microservices framework has built-in support for picocli. Quarkus has a Command Mode with Picocli extension for facilitating the creation of picocli-based CLI applications with Quarkus. Picocli ships with a picocli-spring-boot-starter module that includes a PicocliSpringFactory and Spring Boot auto-configuration to use Spring dependency injection in your picocli command line application. The user manual has examples of integrating with Guice, Spring Boot, Micronaut, Quarkus and with containers that comply to CDI 2.0 specification (JSR 365).

Releases

Documentation

Older

Articles & Presentations

English

русский

Español

Français

Português

日本語

中文

Mailing List

Join the picocli Google group if you are interested in discussing anything picocli-related and receiving announcements on new releases.

Credit

Reallinfo designed the picocli logo! Many thanks!

Commitments

This project follows semantic versioning and adheres to the Zero Bugs Commitment.

Adoption

  • Picocli is now part of Groovy. From Groovy 2.5, all Groovy command line tools are picocli-based, and picocli is the underlying parser for Groovy's CliBuilder DSL.
  • Picocli is now part of Micronaut. The Micronaut CLI has been rewritten with picocli, and Micronaut has dedicated support for running microservices standalone with picocli. See also Micronaut Picocli Guide.
  • Quarkus now offers Command mode with picocli.
  • Picocli is now part of JUnit 5. JUnit 5.3 migrated its ConsoleLauncher from jopt-simple to picocli to support @-files (argument files); this helps users who need to specify many tests on the command line and run into system limitations.
  • Debian now offers a libpicocli-java package. Thanks to Miroslav Kravec.
  • Picocli is used in the Intuit Karate standalone JAR / executable.
  • Picocli is part of Ballerina. Ballerina uses picocli for all its command line utilities.
  • Picocli is used in the CheckStyle standalone JAR / executable from Checkstyle 8.15.
  • Picocli is included in the OpenJDK Quality Outreach list of Free Open Source Software (FOSS) projects that actively test against OpenJDK builds.
  • Picocli is used in the Apache Hadoop Ozone/HDDS command line tools, the Apache Hive benchmark CLI, Apache Ignite TensorFlow, and Apache Sling Feature Model Converter.
  • Picocli is listed on StackShare. Please add it to your stack and add/upvote reasons why you like picocli!
  • Picocli is used in Pinterest ktlint.
  • Picocli is used in Spring IO nohttp-cli.
  • The MinecraftPicocli library facilitates the use of picocli in Minecraft Forge.
  • Simple Java Mail now offers a picocli-based CLI.
  • jbang not only uses picocli internally, but also has a CLI template to generate an initial script: use jbang --init=cli helloworld.java to generate a sample picocli-enabled jbang script. See asciinema.
  • Picocli is the main library used in the CookieTemple cli-java template for building GraalVM native CLI executables in Java. See this preview.
  • Picocli is mentioned in Command Line Interface Guidelines.

Glad to see more people are using picocli. We must be doing something right. :-)

Contribute by helping to promote picocli

If you like picocli, help others discover picocli:

Easy and impactful 😅

  • Give picocli a star on GitHub!
  • Upvote my StackOverflow answer to "How do I parse command line arguments in Java?"
  • Upvote my Quora answer to "What is the best way to parse command-line arguments with Java?"

Spread the joy! 🎉

  • Tweet about picocli! What do you like about it? How has it helped you? How is it different from the alternatives?
  • Mention that your project uses picocli in the documentation of your project.
  • Show that your GitHub project uses picocli, with this badge in your README.md: picocli
[![picocli](https://img.shields.io/badge/picocli-4.7.5-green.svg)](https://github.com/remkop/picocli)

Preach it! 💪

  • Perhaps the most impactful way to show people how picocli can make their life easier is to write a blog post or article, or even do a video!

Example

Annotate fields with the command line parameter names and description. Optionally implement Runnable or Callable to delegate error handling and requests for usage help or version help to picocli. For example:

import picocli.CommandLine;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import java.io.File;

@Command(name = "example", mixinStandardHelpOptions = true, version = "Picocli example 4.0")
public class Example implements Runnable {

    @Option(names = { "-v", "--verbose" },
      description = "Verbose mode. Helpful for troubleshooting. Multiple -v options increase the verbosity.")
    private boolean[] verbose = new boolean[0];

    @Parameters(arity = "1..*", paramLabel = "FILE", description = "File(s) to process.")
    private File[] inputFiles;

    public void run() {
        if (verbose.length > 0) {
            System.out.println(inputFiles.length + " files to process...");
        }
        if (verbose.length > 1) {
            for (File f : inputFiles) {
                System.out.println(f.getAbsolutePath());
            }
        }
    }

    public static void main(String[] args) {
        // By implementing Runnable or Callable, parsing, error handling and handling user
        // requests for usage help or version help can be done with one line of code.

        int exitCode = new CommandLine(new Example()).execute(args);
        System.exit(exitCode);
    }
}

Implement Runnable or Callable, and your command can be executed in one line of code. The example above uses the CommandLine.execute method to parse the command line, handle errors, handle requests for usage and version help, and invoke the business logic. Applications can call System.exit with the returned exit code to signal success or failure to their caller.

$ java Example -v inputFile1 inputFile2

2 files to process...

The CommandLine.execute method automatically prints the usage help message if the user requested help or when the input was invalid.

Usage help message with ANSI colors

This can be customized in many ways. See the user manual section on Executing Commands for details.

Usage Help with ANSI Colors and Styles

Colors, styles, headers, footers and section headings are easily customized with annotations. For example:

Longer help message with ANSI colors

See the source code.

Usage Help API

Picocli annotations offer many ways to customize the usage help message.

If annotations are not sufficient, you can use picocli's Help API to customize even further. For example, your application can generate help like this with a custom layout:

Usage help message with two options per row

See the source code.

Download

You can add picocli as an external dependency to your project, or you can include it as source. See the source code. Copy and paste it into a file called CommandLine.java, add it to your project, and enjoy!

Gradle

implementation 'info.picocli:picocli:4.7.5'

Maven

<dependency>
  <groupId>info.picocli</groupId>
  <artifactId>picocli</artifactId>
  <version>4.7.5</version>
</dependency>

Scala SBT

libraryDependencies += "info.picocli" % "picocli" % "4.7.5"

Ivy

<dependency org="info.picocli" name="picocli" rev="4.7.5" />

Grape

@Grapes(
    @Grab(group='info.picocli', module='picocli', version='4.7.5')
)

Leiningen

[info.picocli/picocli "4.7.5"]

Buildr

'info.picocli:picocli:jar:4.7.5'

JBang

//DEPS info.picocli:picocli:4.7.5

picocli's People

Contributors

ahmede41 avatar bbottema avatar bdemers avatar charphi avatar christrenkamp avatar crotwell avatar danielthegray avatar deining avatar dependabot[bot] avatar dwalluck avatar goooler avatar illes avatar jerrylususu avatar jsotuyod avatar licia-tia avatar madfoal avatar markomackic avatar mattirn avatar newbieorange avatar nicolasmassart avatar querqueq avatar reallinfo avatar remkop avatar rgoldberg avatar rsenden avatar sualeh avatar tisonkun avatar triceo avatar vorburger avatar wtfacoconut avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

picocli's Issues

Support customizable user help format.

Ideally programmers should be able to specify a UsageFormatter interface implementation that gives complete freedom over the usage message layout.

Expose picoCLI usage layout functionality so custom formatters can reuse it.

Customizable:

  • "Usage" line: mention option short form with [-v] optional and mandatory elements, or a generic [OPTIONS] [PARAMETERS]
  • option columns: show in declared order or sort short options first
  • option rows: sort alphabetically or show in declared order
  • required options: show '*' in front of option name, or print 'Required' on 2nd line or print '(Required)' before or after the option description
  • option parameter name: use field name or use field type (class SimpleName)
  • option and parameter separated by space or by '='
  • option parameter default value: print 'Default: VALUE' on 2nd line or print '(default: VALUE)' after the option description

Should CommandLine offer a "starter" function?

Current full usage is:

public static void main(String... args) {
   try {
       MyClass myClass = CommandLine.parse(new MyClass(), args);
       if (myClass.help) {
           CommandLine.usage(MyClass.class, System.out);
       } else if (myClass.version) {
           System.out.println("MyProgram version 1.2.3");
       } else {
           runProgram(myClass);
       }
   } catch (ParameterException ex) { // command line arguments could not be parsed
       System.err.println(ex.getMessage());
       CommandLine.usage(MyClass.class, System.err);
   }
}

Can we reduce the try/catch boilerplate with a convenience method?

public static void main(String... args) {
   MyClass myClass = CommandLine.parseOrPrintUsage(new MyClass(), System.err, args);
   if (myClass == null) { // parsing failed
       return; 
   }
   if (myClass.help) {
       CommandLine.usage(MyClass.class, System.out);
   } else if (myClass.version) {
       System.out.println("MyProgram version 1.2.3");
   } else {
       runProgram(myClass);
   }
}

Add positional @Parameter annotation

This allows positional parameters to be assigned to separate fields with separate types.
usage example: <program> "header text" file1 23 file2 43

class Args {
  @Parameter(position=0, helpText="header text")       String headerText;
  @Parameter(position=1, helpText="binary input file") File binaryInput;
  @Parameter(position=2, helpText="record length")     int recordLength;
  @Parameter(position=3, helpText="text output file")  File output;
  @Parameter(position=4, helpText="max output lines")  int maxLines;
  ...
}

Definition:

@Parameter {
  int position;
  boolean required;
  String helpText;
  boolean hidden;
}

(Introduce a "positional parameters in progress" field?)

Create comparison feature table with prior art

Consider adjusting the column width of the 3rd (long options) column based on the longest value.

The default Columns in a TextTable have a fixed predefined width.
The 3rd column is 24 characters wide by default. Consider adjusting this to a smaller value if all values are less than this width, or if 80-90% of values are less than this width.

Potential drawback is that it may be less predictable for applications to write their description lines in a way that lays out nicely.

i18n

Ideas:

  • @option(..., i18nKey="myKey") -look up myKey in ResourceBundle
  • @option(..., description="A b c d") -look up A_b_c_d in ResourceBundle
  • look up fully qualified field name in ResourceBundle

Detailed usage header should cluster boolean options

Example:

usage: nc [-46CDdhklnrtUuvz] [-I length] [-i interval] [-O length]
          [-P proxy_username] [-p source_port] [-s source] [-T ToS]
          [-V rtable] [-w timeout] [-X proxy_protocol]
          [-x proxy_address[:port]] [destination] [port]

Write user manual

  • options vs positional parameters
  • standalone options are booleans
  • options can take parameters
  • parameters are strongly typed
  • built-in type converters
  • registering custom type converters
  • option short form
  • short form options can be grouped
  • last option in a short option group can take a parameter
  • varargs
  • optional parameters
  • use arity to specify number of required parameters
    (Only allows min, consider supporting max also)
  • option parameters are separated from option name or attached with configurable separator '='

Interpreter should set helpRequested=false before parse()

A CommandLine instance may be reused to parse multiple command line arrays. Ensure any state in the Interpreter is reset to the default at the start of the parse() method.
Especially if a "positional parameters in progress" field is introduced for the proposed @parameter annotation.

Array field values should be preserved (like Collections) and new values appended

Currently array fields (Params or option) are always initialized to a new array instance, regardless of what the current value is.

Collections however are only instantiated when they are initially null, otherwise values are added to the original collection instance.

This asymmetry is undesirable.

Note: we may want to support map-like options like -Da=b -Dx=y. Behaviour for map-like containers should be consistent with arrays and collections.

@Option should not greedily consume args if varargs=false

Example

@Option(names="-words") String[] words;
@Option(names="-v") boolean verbose;

Given command line args -words a b c -v,
the current implementation interprets the "-v" as one of the parameters for word.

An application using picoCLI should be able to designate whether arguments following the option should be greedily consumed or not. This is what the varargs attribute is for. The default for @option is false (as it should be), but the implemented behavior is different.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.