How to properly use execute with programmatic API? #1501
Closed
Kadeluxe
started this conversation in
Show and tell
Replies: 1 comment 3 replies
-
When using the annotations API, your @Command // example that uses the annotations API
class MyCommand implements Runnable {
@Spec CommandSpec spec; // injected by picocli during initialization
@Option(names = "-x") String x; // injected by picocli during parsing (before execution)
public void run() {
// do something with x
}
} In the programmatic API, one idea is to inject the spec yourself: class MyRunnable implements Runnable { // define the business logic
CommandSpec spec; // to be manually injected, see below
public void run() {
ParseResult pr = spec.commandLine().getParseResult(); // get parse result
// see https://picocli.info/picocli-programmatic-api.html#_parse_result
if (pr.hasMatchedOption("-x")) {
// do something because x was specified
}
}
}
MyRunnable myRunnable = new MyRunnable();
CommandSpec spec = CommandSpec.wrapWithoutInspection(myRunnable);
myRunnable.spec = spec; // inject manually
new CommandLine(spec).execute(args); An alternative may be to use |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi!
I'm currently looking for Java command parsing libraries and picocli looks amazing at the first glance, however I'm stuck trying to get a simple example working.
So I want to use it without any annotations. I quickly wrote this to test how it works:
And apparently it works as intended, I can execute both subcommand and top-level command with positional arg.
Now the question is, how do I access parse results inside my
Runnable
s?Like, how do I get
flag1
value inside thatRunnable
ofsubcommand
?Is it even the proper way to do it?
Basically I thought that I can build a command graph using CommandSpecs, then feed the top-level command some string input and picocli would automatically parse and dispatch commands, executing whatever runnables match. Is it correct?
Beta Was this translation helpful? Give feedback.
All reactions