/*
Copyright 2017 Remko Popma
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package picocli;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.text.BreakIterator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import picocli.CommandLine.Help.Ansi.IStyle;
import picocli.CommandLine.Help.Ansi.Style;
import picocli.CommandLine.Help.Ansi.Text;
import picocli.CommandLine.Model.*;
import picocli.CommandLine.ParseResult.MatchedGroup;
import static java.util.Locale.ENGLISH;
import static picocli.CommandLine.Help.Column.Overflow.SPAN;
import static picocli.CommandLine.Help.Column.Overflow.TRUNCATE;
import static picocli.CommandLine.Help.Column.Overflow.WRAP;
/**
*
* CommandLine interpreter that uses reflection to initialize an annotated domain object with values obtained from the
* command line arguments.
*
Example
*
import static picocli.CommandLine.*;
*
* @Command(mixinStandardHelpOptions = true, version = "v3.0.0",
* header = "Encrypt FILE(s), or standard input, to standard output or to the output file.")
* public class Encrypt {
*
* @Parameters(type = File.class, description = "Any number of input files")
* private List<File> files = new ArrayList<File>();
*
* @Option(names = { "-o", "--out" }, description = "Output file (default: print to console)")
* private File outputFile;
*
* @Option(names = { "-v", "--verbose"}, description = "Verbose mode. Helpful for troubleshooting. Multiple -v options increase the verbosity.")
* private boolean[] verbose;
* }
*
*
* Use {@code CommandLine} to initialize a domain object as follows:
*
* public static void main(String... args) {
* Encrypt encrypt = new Encrypt();
* try {
* ParseResult parseResult = new CommandLine(encrypt).parseArgs(args);
* if (!CommandLine.printHelpIfRequested(parseResult)) {
* runProgram(encrypt);
* }
* } catch (ParameterException ex) { // command line arguments could not be parsed
* System.err.println(ex.getMessage());
* ex.getCommandLine().usage(System.err);
* }
* }
*
* Invoke the above program with some command line arguments. The below are all equivalent:
*
* Another example that implements {@code Callable} and uses the {@link #call(Callable, String...) CommandLine.call} convenience API to run in a single line of code:
*
*
* @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<Void> {
*
* @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 = "MD5";
*
* public static void main(String[] args) throws Exception {
* // 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.
* CommandLine.call(new CheckSum(), args);
* }
*
* @Override
* public Void call() throws Exception {
* // your business logic goes here...
* byte[] fileContents = Files.readAllBytes(file.toPath());
* byte[] digest = MessageDigest.getInstance(algorithm).digest(fileContents);
* System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(digest));
* return null;
* }
* }
*
*
Classes and Interfaces for Defining a CommandSpec Model
*
*
*
*
Classes Related to Parsing Command Line Arguments
*
*
*
*/
public class CommandLine {
/** This is picocli version {@value}. */
public static final String VERSION = "4.0.0-alpha-2-SNAPSHOT";
private final Tracer tracer = new Tracer();
private final CommandSpec commandSpec;
private final Interpreter interpreter;
private final IFactory factory;
/**
* Constructs a new {@code CommandLine} interpreter with the specified object (which may be an annotated user object or a {@link CommandSpec CommandSpec}) and a default subcommand factory.
*
The specified object may be a {@link CommandSpec CommandSpec} object, or it may be a {@code @Command}-annotated
* user object with {@code @Option} and {@code @Parameters}-annotated fields, in which case picocli automatically
* constructs a {@code CommandSpec} from this user object.
*
* When the {@link #parse(String...)} method is called, the {@link CommandSpec CommandSpec} object will be
* initialized based on command line arguments. If the commandSpec is created from an annotated user object, this
* user object will be initialized based on the command line arguments.
* @param command an annotated user object or a {@code CommandSpec} object to initialize from the command line arguments
* @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
*/
public CommandLine(Object command) {
this(command, new DefaultFactory());
}
/**
* Constructs a new {@code CommandLine} interpreter with the specified object (which may be an annotated user object or a {@link CommandSpec CommandSpec}) and object factory.
*
The specified object may be a {@link CommandSpec CommandSpec} object, or it may be a {@code @Command}-annotated
* user object with {@code @Option} and {@code @Parameters}-annotated fields, in which case picocli automatically
* constructs a {@code CommandSpec} from this user object.
*
If the specified command object is an interface {@code Class} with {@code @Option} and {@code @Parameters}-annotated methods,
* picocli creates a {@link java.lang.reflect.Proxy Proxy} whose methods return the matched command line values.
* If the specified command object is a concrete {@code Class}, picocli delegates to the {@linkplain IFactory factory} to get an instance.
*
* When the {@link #parse(String...)} method is called, the {@link CommandSpec CommandSpec} object will be
* initialized based on command line arguments. If the commandSpec is created from an annotated user object, this
* user object will be initialized based on the command line arguments.
* @param command an annotated user object or a {@code CommandSpec} object to initialize from the command line arguments
* @param factory the factory used to create instances of {@linkplain Command#subcommands() subcommands}, {@linkplain Option#converter() converters}, etc., that are registered declaratively with annotation attributes
* @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
* @since 2.2 */
public CommandLine(Object command, IFactory factory) {
this.factory = Assert.notNull(factory, "factory");
interpreter = new Interpreter();
commandSpec = CommandSpec.forAnnotatedObject(command, factory);
commandSpec.commandLine(this);
commandSpec.validate();
if (commandSpec.unmatchedArgsBindings().size() > 0) { setUnmatchedArgumentsAllowed(true); }
}
/**
* Returns the {@code CommandSpec} model that this {@code CommandLine} was constructed with.
* @return the {@code CommandSpec} model
* @since 3.0 */
public CommandSpec getCommandSpec() { return commandSpec; }
/**
* Adds the options and positional parameters in the specified mixin to this command.
*
The specified object may be a {@link CommandSpec CommandSpec} object, or it may be a user object with
* {@code @Option} and {@code @Parameters}-annotated fields, in which case picocli automatically
* constructs a {@code CommandSpec} from this user object.
*
* @param name the name by which the mixin object may later be retrieved
* @param mixin an annotated user object or a {@link CommandSpec CommandSpec} object whose options and positional parameters to add to this command
* @return this CommandLine object, to allow method chaining
* @since 3.0 */
public CommandLine addMixin(String name, Object mixin) {
getCommandSpec().addMixin(name, CommandSpec.forAnnotatedObject(mixin, factory));
return this;
}
/**
* Returns a map of user objects whose options and positional parameters were added to ("mixed in" with) this command.
* @return a new Map containing the user objects mixed in with this command. If {@code CommandSpec} objects without
* user objects were programmatically added, use the {@link CommandSpec#mixins() underlying model} directly.
* @since 3.0 */
public Map getMixins() {
Map mixins = getCommandSpec().mixins();
Map result = new LinkedHashMap();
for (String name : mixins.keySet()) { result.put(name, mixins.get(name).userObject); }
return result;
}
/** Registers a subcommand with the specified name. For example:
*
* CommandLine commandLine = new CommandLine(new Git())
* .addSubcommand("status", new GitStatus())
* .addSubcommand("commit", new GitCommit();
* .addSubcommand("add", new GitAdd())
* .addSubcommand("branch", new GitBranch())
* .addSubcommand("checkout", new GitCheckout())
* //...
* ;
*
*
*
The specified object can be an annotated object or a
* {@code CommandLine} instance with its own nested subcommands. For example:
*
* CommandLine commandLine = new CommandLine(new MainCommand())
* .addSubcommand("cmd1", new ChildCommand1()) // subcommand
* .addSubcommand("cmd2", new ChildCommand2())
* .addSubcommand("cmd3", new CommandLine(new ChildCommand3()) // subcommand with nested sub-subcommands
* .addSubcommand("cmd3sub1", new GrandChild3Command1())
* .addSubcommand("cmd3sub2", new GrandChild3Command2())
* .addSubcommand("cmd3sub3", new CommandLine(new GrandChild3Command3()) // deeper nesting
* .addSubcommand("cmd3sub3sub1", new GreatGrandChild3Command3_1())
* .addSubcommand("cmd3sub3sub2", new GreatGrandChild3Command3_2())
* )
* );
*
*
The default type converters are available on all subcommands and nested sub-subcommands, but custom type
* converters are registered only with the subcommand hierarchy as it existed when the custom type was registered.
* To ensure a custom type converter is available to all subcommands, register the type converter last, after
* adding subcommands.
*
See also the {@link Command#subcommands()} annotation to register subcommands declaratively.
*
* @param name the string to recognize on the command line as a subcommand
* @param command the object to initialize with command line arguments following the subcommand name.
* This may be a {@code CommandLine} instance with its own (nested) subcommands
* @return this CommandLine object, to allow method chaining
* @see #registerConverter(Class, ITypeConverter)
* @since 0.9.7
* @see Command#subcommands()
*/
public CommandLine addSubcommand(String name, Object command) {
return addSubcommand(name, command, new String[0]);
}
/** Registers a subcommand with the specified name and all specified aliases. See also {@link #addSubcommand(String, Object)}.
*
*
* @param name the string to recognize on the command line as a subcommand
* @param command the object to initialize with command line arguments following the subcommand name.
* This may be a {@code CommandLine} instance with its own (nested) subcommands
* @param aliases zero or more alias names that are also recognized on the command line as this subcommand
* @return this CommandLine object, to allow method chaining
* @since 3.1
* @see #addSubcommand(String, Object)
*/
public CommandLine addSubcommand(String name, Object command, String... aliases) {
CommandLine subcommandLine = toCommandLine(command, factory);
subcommandLine.getCommandSpec().aliases.addAll(Arrays.asList(aliases));
getCommandSpec().addSubcommand(name, subcommandLine);
CommandLine.Model.CommandReflection.initParentCommand(subcommandLine.getCommandSpec().userObject(), getCommandSpec().userObject());
return this;
}
/** Returns a map with the subcommands {@linkplain #addSubcommand(String, Object) registered} on this instance.
* @return a map with the registered subcommands
* @since 0.9.7
*/
public Map getSubcommands() {
return new LinkedHashMap(getCommandSpec().subcommands());
}
/**
* Returns the command that this is a subcommand of, or {@code null} if this is a top-level command.
* @return the command that this is a subcommand of, or {@code null} if this is a top-level command
* @see #addSubcommand(String, Object)
* @see Command#subcommands()
* @since 0.9.8
*/
public CommandLine getParent() {
CommandSpec parent = getCommandSpec().parent();
return parent == null ? null : parent.commandLine();
}
/** Returns the annotated user object that this {@code CommandLine} instance was constructed with.
* @param the type of the variable that the return value is being assigned to
* @return the annotated object that this {@code CommandLine} instance was constructed with
* @since 0.9.7
*/
@SuppressWarnings("unchecked")
public T getCommand() {
return (T) getCommandSpec().userObject();
}
/** Returns {@code true} if an option annotated with {@link Option#usageHelp()} was specified on the command line.
* @return whether the parser encountered an option annotated with {@link Option#usageHelp()}.
* @since 0.9.8 */
public boolean isUsageHelpRequested() { return interpreter.parseResultBuilder != null && interpreter.parseResultBuilder.usageHelpRequested; }
/** Returns {@code true} if an option annotated with {@link Option#versionHelp()} was specified on the command line.
* @return whether the parser encountered an option annotated with {@link Option#versionHelp()}.
* @since 0.9.8 */
public boolean isVersionHelpRequested() { return interpreter.parseResultBuilder != null && interpreter.parseResultBuilder.versionHelpRequested; }
/** Returns the {@code IHelpFactory} that is used to construct the usage help message.
* @see #setHelpFactory(IHelpFactory)
* @since 3.9
*/
public IHelpFactory getHelpFactory() {
return getCommandSpec().usageMessage().helpFactory();
}
/** Sets a new {@code IHelpFactory} to customize the usage help message.
* @param helpFactory the new help factory. Must be non-{@code null}.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
* @return this {@code CommandLine} object, to allow method chaining
* @since 3.9
*/
public CommandLine setHelpFactory(IHelpFactory helpFactory) {
getCommandSpec().usageMessage().helpFactory(helpFactory);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setHelpFactory(helpFactory);
}
return this;
}
/**
* Returns the section keys in the order that the usage help message should render the sections.
* This ordering may be modified with {@link #setHelpSectionKeys(List) setSectionKeys}. The default keys are (in order):
*
*
*
* @since 3.9
*/
public List getHelpSectionKeys() { return getCommandSpec().usageMessage().sectionKeys(); }
/**
* Sets the section keys in the order that the usage help message should render the sections.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
*
Use {@link UsageMessageSpec#sectionKeys(List)} to customize a command without affecting its subcommands.
* @see #getHelpSectionKeys
* @since 3.9
*/
public CommandLine setHelpSectionKeys(List keys) {
getCommandSpec().usageMessage().sectionKeys(keys);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setHelpSectionKeys(keys);
}
return this;
}
/**
* Returns the map of section keys and renderers used to construct the usage help message.
* The usage help message can be customized by adding, replacing and removing section renderers from this map.
* Sections can be reordered with {@link #setHelpSectionKeys(List) setSectionKeys}.
* Sections that are either not in this map or not in the list returned by {@link #getHelpSectionKeys() getSectionKeys} are omitted.
*
* NOTE: By modifying the returned {@code Map}, only the usage help message of this command is affected.
* Use {@link #setHelpSectionMap(Map)} to customize the usage help message for this command and all subcommands.
*
* @since 3.9
*/
public Map getHelpSectionMap() { return getCommandSpec().usageMessage().sectionMap(); }
/**
* Sets the map of section keys and renderers used to construct the usage help message.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
*
Use {@link UsageMessageSpec#sectionMap(Map)} to customize a command without affecting its subcommands.
* @see #getHelpSectionMap
* @since 3.9
*/
public CommandLine setHelpSectionMap(Map map) {
getCommandSpec().usageMessage().sectionMap(map);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setHelpSectionMap(map);
}
return this;
}
/** Returns whether the value of boolean flag options should be "toggled" when the option is matched.
* By default, flags are toggled, so if the value is {@code true} it is set to {@code false}, and when the value is
* {@code false} it is set to {@code true}. If toggling is off, flags are simply set to {@code true}.
* @return {@code true} the value of boolean flag options should be "toggled" when the option is matched, {@code false} otherwise
* @since 3.0
*/
public boolean isToggleBooleanFlags() {
return getCommandSpec().parser().toggleBooleanFlags();
}
/** Sets whether the value of boolean flag options should be "toggled" when the option is matched. The default is {@code true}.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
* @param newValue the new setting
* @return this {@code CommandLine} object, to allow method chaining
* @since 3.0
*/
public CommandLine setToggleBooleanFlags(boolean newValue) {
getCommandSpec().parser().toggleBooleanFlags(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setToggleBooleanFlags(newValue);
}
return this;
}
/** Returns whether options for single-value fields can be specified multiple times on the command line.
* The default is {@code false} and a {@link OverwrittenOptionException} is thrown if this happens.
* When {@code true}, the last specified value is retained.
* @return {@code true} if options for single-value fields can be specified multiple times on the command line, {@code false} otherwise
* @since 0.9.7
*/
public boolean isOverwrittenOptionsAllowed() {
return getCommandSpec().parser().overwrittenOptionsAllowed();
}
/** Sets whether options for single-value fields can be specified multiple times on the command line without a {@link OverwrittenOptionException} being thrown.
* The default is {@code false}.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
* @param newValue the new setting
* @return this {@code CommandLine} object, to allow method chaining
* @since 0.9.7
*/
public CommandLine setOverwrittenOptionsAllowed(boolean newValue) {
getCommandSpec().parser().overwrittenOptionsAllowed(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setOverwrittenOptionsAllowed(newValue);
}
return this;
}
/** Returns whether the parser accepts clustered short options. The default is {@code true}.
* @return {@code true} if short options like {@code -x -v -f SomeFile} can be clustered together like {@code -xvfSomeFile}, {@code false} otherwise
* @since 3.0 */
public boolean isPosixClusteredShortOptionsAllowed() { return getCommandSpec().parser().posixClusteredShortOptionsAllowed(); }
/** Sets whether short options like {@code -x -v -f SomeFile} can be clustered together like {@code -xvfSomeFile}. The default is {@code true}.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
* @param newValue the new setting
* @return this {@code CommandLine} object, to allow method chaining
* @since 3.0
*/
public CommandLine setPosixClusteredShortOptionsAllowed(boolean newValue) {
getCommandSpec().parser().posixClusteredShortOptionsAllowed(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setPosixClusteredShortOptionsAllowed(newValue);
}
return this;
}
/** Returns whether the parser should ignore case when converting arguments to {@code enum} values. The default is {@code false}.
* @return {@code true} if enum values can be specified that don't match the {@code toString()} value of the enum constant, {@code false} otherwise;
* e.g., for an option of type java.time.DayOfWeek,
* values {@code MonDaY}, {@code monday} and {@code MONDAY} are all recognized if {@code true}.
* @since 3.4 */
public boolean isCaseInsensitiveEnumValuesAllowed() { return getCommandSpec().parser().caseInsensitiveEnumValuesAllowed(); }
/** Sets whether the parser should ignore case when converting arguments to {@code enum} values. The default is {@code false}.
* When set to true, for example, for an option of type java.time.DayOfWeek,
* values {@code MonDaY}, {@code monday} and {@code MONDAY} are all recognized if {@code true}.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
* @param newValue the new setting
* @return this {@code CommandLine} object, to allow method chaining
* @since 3.4
*/
public CommandLine setCaseInsensitiveEnumValuesAllowed(boolean newValue) {
getCommandSpec().parser().caseInsensitiveEnumValuesAllowed(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setCaseInsensitiveEnumValuesAllowed(newValue);
}
return this;
}
/** Returns whether the parser should trim quotes from command line arguments before processing them. The default is
* read from the system property "picocli.trimQuotes" and will be {@code true} if the property is present and empty,
* or if its value is "true".
* @return {@code true} if the parser should trim quotes from command line arguments before processing them, {@code false} otherwise;
* @since 3.7 */
public boolean isTrimQuotes() { return getCommandSpec().parser().trimQuotes(); }
/** Sets whether the parser should trim quotes from command line arguments before processing them. The default is
* read from the system property "picocli.trimQuotes" and will be {@code true} if the property is set and empty, or
* if its value is "true".
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
*
Calling this method will cause the "picocli.trimQuotes" property to have no effect.
* @param newValue the new setting
* @return this {@code CommandLine} object, to allow method chaining
* @since 3.7
*/
public CommandLine setTrimQuotes(boolean newValue) {
getCommandSpec().parser().trimQuotes(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setTrimQuotes(newValue);
}
return this;
}
/** Returns whether the parser is allowed to split quoted Strings or not. The default is {@code false},
* so quoted strings are treated as a single value that cannot be split.
* @return {@code true} if the parser is allowed to split quoted Strings, {@code false} otherwise;
* @see ArgSpec#splitRegex()
* @since 3.7 */
public boolean isSplitQuotedStrings() { return getCommandSpec().parser().splitQuotedStrings(); }
/** Sets whether the parser is allowed to split quoted Strings. The default is {@code false}.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
* @param newValue the new setting
* @return this {@code CommandLine} object, to allow method chaining
* @see ArgSpec#splitRegex()
* @since 3.7
*/
public CommandLine setSplitQuotedStrings(boolean newValue) {
getCommandSpec().parser().splitQuotedStrings(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setSplitQuotedStrings(newValue);
}
return this;
}
/** Returns the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters.
* @return the end-of-options delimiter. The default is {@code "--"}.
* @since 3.5 */
public String getEndOfOptionsDelimiter() { return getCommandSpec().parser().endOfOptionsDelimiter(); }
/** Sets the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters.
* @param delimiter the end-of-options delimiter; must not be {@code null}. The default is {@code "--"}.
* @return this {@code CommandLine} object, to allow method chaining
* @since 3.5 */
public CommandLine setEndOfOptionsDelimiter(String delimiter) {
getCommandSpec().parser().endOfOptionsDelimiter(delimiter);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setEndOfOptionsDelimiter(delimiter);
}
return this;
}
/** Returns the default value provider for the command, or {@code null} if none has been set.
* @return the default value provider for this command, or {@code null}
* @since 3.6
* @see Command#defaultValueProvider()
* @see CommandSpec#defaultValueProvider()
* @see ArgSpec#defaultValueString()
*/
public IDefaultValueProvider getDefaultValueProvider() {
return getCommandSpec().defaultValueProvider();
}
/** Sets a default value provider for the command and sub-commands
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* sub-commands and nested sub-subcommands at the moment this method is called. Sub-commands added
* later will have the default setting. To ensure a setting is applied to all
* sub-commands, call the setter last, after adding sub-commands.
* @param newValue the default value provider to use
* @return this {@code CommandLine} object, to allow method chaining
* @since 3.6
*/
public CommandLine setDefaultValueProvider(IDefaultValueProvider newValue) {
getCommandSpec().defaultValueProvider(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setDefaultValueProvider(newValue);
}
return this;
}
/** Returns whether the parser interprets the first positional parameter as "end of options" so the remaining
* arguments are all treated as positional parameters. The default is {@code false}.
* @return {@code true} if all values following the first positional parameter should be treated as positional parameters, {@code false} otherwise
* @since 2.3
*/
public boolean isStopAtPositional() {
return getCommandSpec().parser().stopAtPositional();
}
/** Sets whether the parser interprets the first positional parameter as "end of options" so the remaining
* arguments are all treated as positional parameters. The default is {@code false}.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
* @param newValue {@code true} if all values following the first positional parameter should be treated as positional parameters, {@code false} otherwise
* @return this {@code CommandLine} object, to allow method chaining
* @since 2.3
*/
public CommandLine setStopAtPositional(boolean newValue) {
getCommandSpec().parser().stopAtPositional(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setStopAtPositional(newValue);
}
return this;
}
/** Returns whether the parser should stop interpreting options and positional parameters as soon as it encounters an
* unmatched option. Unmatched options are arguments that look like an option but are not one of the known options, or
* positional arguments for which there is no available slots (the command has no positional parameters or their size is limited).
* The default is {@code false}.
*
Setting this flag to {@code true} automatically sets the {@linkplain #isUnmatchedArgumentsAllowed() unmatchedArgumentsAllowed} flag to {@code true} also.
* @return {@code true} when an unmatched option should result in the remaining command line arguments to be added to the
* {@linkplain #getUnmatchedArguments() unmatchedArguments list}
* @since 2.3
*/
public boolean isStopAtUnmatched() {
return getCommandSpec().parser().stopAtUnmatched();
}
/** Sets whether the parser should stop interpreting options and positional parameters as soon as it encounters an
* unmatched option. Unmatched options are arguments that look like an option but are not one of the known options, or
* positional arguments for which there is no available slots (the command has no positional parameters or their size is limited).
* The default is {@code false}.
*
Setting this flag to {@code true} automatically sets the {@linkplain #setUnmatchedArgumentsAllowed(boolean) unmatchedArgumentsAllowed} flag to {@code true} also.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
* @param newValue {@code true} when an unmatched option should result in the remaining command line arguments to be added to the
* {@linkplain #getUnmatchedArguments() unmatchedArguments list}
* @return this {@code CommandLine} object, to allow method chaining
* @since 2.3
*/
public CommandLine setStopAtUnmatched(boolean newValue) {
getCommandSpec().parser().stopAtUnmatched(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setStopAtUnmatched(newValue);
}
if (newValue) { setUnmatchedArgumentsAllowed(true); }
return this;
}
/** Returns whether arguments on the command line that resemble an option should be treated as positional parameters.
* The default is {@code false} and the parser behaviour depends on {@link #isUnmatchedArgumentsAllowed()}.
* @return {@code true} arguments on the command line that resemble an option should be treated as positional parameters, {@code false} otherwise
* @see #getUnmatchedArguments()
* @since 3.0
*/
public boolean isUnmatchedOptionsArePositionalParams() {
return getCommandSpec().parser().unmatchedOptionsArePositionalParams();
}
/** Sets whether arguments on the command line that resemble an option should be treated as positional parameters.
* The default is {@code false}.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
* @param newValue the new setting. When {@code true}, arguments on the command line that resemble an option should be treated as positional parameters.
* @return this {@code CommandLine} object, to allow method chaining
* @since 3.0
* @see #getUnmatchedArguments()
* @see #isUnmatchedArgumentsAllowed
*/
public CommandLine setUnmatchedOptionsArePositionalParams(boolean newValue) {
getCommandSpec().parser().unmatchedOptionsArePositionalParams(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setUnmatchedOptionsArePositionalParams(newValue);
}
return this;
}
/** Returns whether the end user may specify arguments on the command line that are not matched to any option or parameter fields.
* The default is {@code false} and a {@link UnmatchedArgumentException} is thrown if this happens.
* When {@code true}, the last unmatched arguments are available via the {@link #getUnmatchedArguments()} method.
* @return {@code true} if the end use may specify unmatched arguments on the command line, {@code false} otherwise
* @see #getUnmatchedArguments()
* @since 0.9.7
*/
public boolean isUnmatchedArgumentsAllowed() {
return getCommandSpec().parser().unmatchedArgumentsAllowed();
}
/** Sets whether the end user may specify unmatched arguments on the command line without a {@link UnmatchedArgumentException} being thrown.
* The default is {@code false}.
*
The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
* subcommands and nested sub-subcommands at the moment this method is called. Subcommands added
* later will have the default setting. To ensure a setting is applied to all
* subcommands, call the setter last, after adding subcommands.
* @param newValue the new setting. When {@code true}, the last unmatched arguments are available via the {@link #getUnmatchedArguments()} method.
* @return this {@code CommandLine} object, to allow method chaining
* @since 0.9.7
* @see #getUnmatchedArguments()
*/
public CommandLine setUnmatchedArgumentsAllowed(boolean newValue) {
getCommandSpec().parser().unmatchedArgumentsAllowed(newValue);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setUnmatchedArgumentsAllowed(newValue);
}
return this;
}
/** Returns the list of unmatched command line arguments, if any.
* @return the list of unmatched command line arguments or an empty list
* @see #isUnmatchedArgumentsAllowed()
* @since 0.9.7
*/
public List getUnmatchedArguments() {
return interpreter.parseResultBuilder == null ? Collections.emptyList() : UnmatchedArgumentException.stripErrorMessage(interpreter.parseResultBuilder.unmatched);
}
/**
*
* Convenience method that initializes the specified annotated object from the specified command line arguments.
*
*
* @param command the object to initialize. This object contains fields annotated with
* {@code @Option} or {@code @Parameters}.
* @param args the command line arguments to parse
* @param the type of the annotated object
* @return the specified annotated object
* @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
* @throws ParameterException if the specified command line arguments are invalid
* @since 0.9.7
*/
public static T populateCommand(T command, String... args) {
CommandLine cli = toCommandLine(command, new DefaultFactory());
cli.parse(args);
return command;
}
/**
*
* Convenience method that derives the command specification from the specified interface class, and returns an
* instance of the specified interface. The interface is expected to have annotated getter methods. Picocli will
* instantiate the interface and the getter methods will return the option and positional parameter values matched on the command line.
*
*
* @param spec the interface that defines the command specification. This object contains getter methods annotated with
* {@code @Option} or {@code @Parameters}.
* @param args the command line arguments to parse
* @param the type of the annotated object
* @return an instance of the specified annotated interface
* @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
* @throws ParameterException if the specified command line arguments are invalid
* @since 3.1
*/
public static T populateSpec(Class spec, String... args) {
CommandLine cli = toCommandLine(spec, new DefaultFactory());
cli.parse(args);
return cli.getCommand();
}
/** Parses the specified command line arguments and returns a list of {@code CommandLine} objects representing the
* top-level command and any subcommands (if any) that were recognized and initialized during the parsing process.
*
* If parsing succeeds, the first element in the returned list is always {@code this CommandLine} object. The
* returned list may contain more elements if subcommands were {@linkplain #addSubcommand(String, Object) registered}
* and these subcommands were initialized by matching command line arguments. If parsing fails, a
* {@link ParameterException} is thrown.
*
*
* @param args the command line arguments to parse
* @return a list with the top-level command and any subcommands initialized by this method
* @throws ParameterException if the specified command line arguments are invalid; use
* {@link ParameterException#getCommandLine()} to get the command or subcommand whose user input was invalid
*/
public List parse(String... args) {
return interpreter.parse(args);
}
/** Parses the specified command line arguments and returns a list of {@code ParseResult} with the options, positional
* parameters, and subcommands (if any) that were recognized and initialized during the parsing process.
*
If parsing fails, a {@link ParameterException} is thrown.
*
* @param args the command line arguments to parse
* @return a list with the top-level command and any subcommands initialized by this method
* @throws ParameterException if the specified command line arguments are invalid; use
* {@link ParameterException#getCommandLine()} to get the command or subcommand whose user input was invalid
*/
public ParseResult parseArgs(String... args) {
interpreter.parse(args);
return getParseResult();
}
public ParseResult getParseResult() { return interpreter.parseResultBuilder == null ? null : interpreter.parseResultBuilder.build(); }
/**
* Represents a function that can process a List of {@code CommandLine} objects resulting from successfully
* {@linkplain #parse(String...) parsing} the command line arguments. This is a
* functional interface
* whose functional method is {@link #handleParseResult(List, PrintStream, CommandLine.Help.Ansi)}.
*
* Implementations of this functions can be passed to the {@link #parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...) CommandLine::parseWithHandler}
* methods to take some next step after the command line was successfully parsed.
*
* @see RunFirst
* @see RunLast
* @see RunAll
* @deprecated Use {@link IParseResultHandler2} instead.
* @since 2.0 */
@Deprecated public static interface IParseResultHandler {
/** Processes a List of {@code CommandLine} objects resulting from successfully
* {@linkplain #parse(String...) parsing} the command line arguments and optionally returns a list of results.
* @param parsedCommands the {@code CommandLine} objects that resulted from successfully parsing the command line arguments
* @param out the {@code PrintStream} to print help to if requested
* @param ansi for printing help messages using ANSI styles and colors
* @return a list of results, or an empty list if there are no results
* @throws ParameterException if a help command was invoked for an unknown subcommand. Any {@code ParameterExceptions}
* thrown from this method are treated as if this exception was thrown during parsing and passed to the {@link IExceptionHandler}
* @throws ExecutionException if a problem occurred while processing the parse results; use
* {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
*/
List