我的问题与问到here的问题相似,也很简单。
我有三个选项,-A、-A1、-A2 (概念上,属于单个组)。所需的关系如下:
这两个都不是required
-A,应该与至少一个-A1或-A2
-A1一起给出,-A2可以给出一个单独的-A。
换言之:
-A -A1 -A2
-A -A1、-A -A2和规范:-A、-A1、-A2和-A1 -A2这就是我所使用的两个@ArgGroups:
import picocli.CommandLine;
import picocli.CommandLine.*;
import picocli.CommandLine.Model.CommandSpec;
public class App implements Runnable {
static class MyGroupX {
@Option(names="-A1", required=false) boolean A1;
@Option(names="-A2", required=false) boolean A2;
}
static class MyGroup {
@Option(names="-A", required=true) boolean A;
@ArgGroup(exclusive=false, multiplicity="1") MyGroupX myGroupX;
}
@ArgGroup(exclusive=false) MyGroup myGroup;
@Spec CommandSpec spec;
@Override
public void run() {
System.out.printf("OK: %s%n", spec.commandLine().getParseResult().originalArgs());
}
public static void main(String[] args) {
//test: these should be valid
new CommandLine(new App()).execute();
new CommandLine(new App()).execute("-A -A1".split(" "));
new CommandLine(new App()).execute("-A -A2".split(" "));
new CommandLine(new App()).execute("-A -A1 -A2".split(" "));
//test: these should FAIL
new CommandLine(new App()).execute("-A");
new CommandLine(new App()).execute("-A1");
new CommandLine(new App()).execute("-A2");
new CommandLine(new App()).execute("-A1 -A2".split(" "));
}
}有更简单的方法吗?
谢谢!
发布于 2020-05-23 01:48:43
有些关系不能仅用@ArgGroup注释来表示,在这种情况下,需要应用程序中的自定义验证逻辑。
但是,对于您的应用程序来说,情况并非如此。在我看来,您已经找到了一种非常紧凑的方式来表达您的需求。
有效的用户输入序列-A -A1、-A -A2和-A -A1 -A2都被接受。
无效的用户输入序列都被拒绝,并带有相当清晰的错误消息:
Input Error message
----- -------------
-A Missing required argument(s): ([-A1] [-A2])
-A1 Missing required argument(s): -A
-A2 Missing required argument(s): -A
-A1 -A2 Missing required argument(s): -A在代码中没有任何显式验证逻辑的情况下,应用程序实现了所有这一切,所有这些都是通过声明性的注释完成的。任务完成了,我想说。我看不出有什么办法能进一步改善这一点。
https://stackoverflow.com/questions/61963756
复制相似问题