【问题标题】:picocli : dependent arguments in ArgGrouppicocli : ArgGroup 中的依赖参数
【发布时间】:2020-09-09 19:26:03
【问题描述】:

我的问题与here 提出的问题类似,也更简单。

我有三个选项,-A-A1-A2(从概念上讲,属于单个组)。所需的关系如下:

  1. 这些都不是必需的
  2. -A 应与-A1-A2 中的至少一个一起提供
  3. -A1-A2 都可以用一个 -A 给出

换句话说:

  • 有效规格:-A -A1-A -A2-A -A1 -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(" "));
    }
}

有没有更简单的方法?

谢谢!

【问题讨论】:

    标签: picocli


    【解决方案1】:

    某些关系不能仅使用 @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
    

    应用程序在代码中没有任何明确的验证逻辑就实现了这一切,这一切都是通过注释以声明方式完成的。任务完成了,我想说。我看不出有进一步改进的方法。

    【讨论】:

    • 我同意它足够紧凑。所以,我没有错过任何东西。很高兴知道。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多