What's the picocli idiomatic way to implement subcommands?
See original GitHub issueI have this code that implements a main command that basically only prints usage and two subcommands that actually do things. What’s the idiomatic picocli way that invokes specific code based on the subcommand used and correctly gives user feedback (prints error and usage) in case the subcommand had invalid parameters given?
If i use the code that parses subcommands given in the documentation that is List<CommandLine> parsed = commandLine.parse(args);
this explodes if any of the parameters were incorrect that were given to subcommands and there’s no way to figure out which subcommand was invoked so you could print the correct subcommand’s usage for the user.
On the other hand the picocli documentation suggests to use Object result = CommandLine.call(new MyCallable(), System.err, args);
which automatically catches exceptions and prints proper usage, but this doesn’t seem to support subcommands directly, or at least I can’t figure out from the documentation how it could be used with subcommands directly.
Here’s the code that I ended up using, is there a better way?
@Command(name = "import",
description = "Import <redacted things>, validate and do something with their content based on the given subcommand",
subcommands = {
Print.class, Import.class
}
)
public class MainApplication implements Callable<Void> {
public static void main(String[] args) throws Exception {
if (args.length > 0 && args[0].equalsIgnoreCase(("print"))) {
CommandLine.call(new Print(), System.err, Arrays.copyOfRange(args, 1, args.length));
}
else if (args.length > 0 && args[0].equalsIgnoreCase("import")) {
CommandLine.call(new Import(), System.err, Arrays.copyOfRange(args, 1, args.length));
}
else {
CommandLine.call(new MainApplication(), System.err, args);
}
}
@Override
public Void call() throws Exception {
CommandLine.usage(this, System.err);
return null;
}
}
The Import and Print classes implement Callable<Void> as well and their call methods actually invoke the functionality that their subcommands should do.
Issue Analytics
- State:
- Created 6 years ago
- Comments:10 (7 by maintainers)
I created #207 to Provide ability to find which subcommand threw a ParameterException.
@RailRunner166 Thanks for the feedback. Don’t forget to star the project if you like it! 😉