由于子命令支持(和基于注释的声明),我从 Apache Commons CLI 切换到 Picocli。
考虑一个命令行工具,比如git
,带有子命令,比如push
. Git 有一个主开关--verbose
或用于在所有子命令-v
中启用详细模式。如何实现在任何子命令之前执行的主开关?
这是我的测试
@CommandLine.Command(name = "push",
description = "Update remote refs along with associated objects")
class PushCommand implements Callable<Void> {
@Override
public Void call() throws Exception {
System.out.println("#PushCommand.call");
return null;
}
}
@CommandLine.Command(description = "Version control", subcommands = {PushCommand.class})
public class GitApp implements Callable<Void> {
@CommandLine.Option(names = {"-h", "--help"}, usageHelp = true, description = "Display this help message.")
private boolean usageHelpRequested;
@CommandLine.Option(names = {"-v", "--verbose"}, description = "Verbose mode. Helpful for troubleshooting.")
private boolean verboseMode;
public static void main(String[] args) {
GitApp app = new GitApp();
CommandLine.call(app, "--verbose", "push");
System.out.println("#GitApp.main after. verbose: " + (app.verboseMode));
}
@Override
public Void call() throws Exception {
System.out.println("#GitApp.call");
return null;
}
}
输出是
#PushCommand.call
#GitApp.main after. verbose: true
我希望,GitApp.call
在调用子命令之前调用它。但只有 sub 命令被调用。