Search code examples
javapicocli

PicoCli Mutually Dependent Options question (resolve values)


I have the following code below.

My use case is that when using option --install you must also use the option --version. This is working well when using the below Dependent group.

However I am unable to get the a value of variable version. How do i extract/resolve it? Is there any way i can do it from the call() method?

@CommandLine.Command(name = "rt")
@Component
public class Artifactory implements Callable<Integer> {


    @CommandLine.ArgGroup(exclusive = false)
    Dependent dependent;

    static class Dependent{
        @CommandLine.Option(names = {"-i", "--install"}, description = "The Artifactory version")
        boolean install;

        @CommandLine.Option(names = {"-v", "--version"}, required = false, description = "The Artifactory version")
        String version;
    }

    @Override
    public Integer call() throws Exception {
        System.out.println("We are installing Artifactory version from @Artifactory: " + version);
        return 0;
    }

}

Thanks for the help :D


Solution

  • You should be able to get the specified values from the dependent field in the Artifactory class. For example:

    @Command(name = "rt")
    @Component
    public class Artifactory implements Callable<Integer> {
    
    
        @ArgGroup(exclusive = false, multiplicity = "1")
        Dependent dependent;
    
        static class Dependent{
            @Option(names = {"-i", "--install"}, description = "Install or not.")
            boolean install;
    
            @Option(names = {"-v", "--version"}, required = false,
              description = "The Artifactory version.")
            String version;
        }
    
        @Override
        public Integer call() throws Exception {
            // I made the arg-group multiplicity=1, so it cannot be `null`.
            // The default is `multiplicity = "0..1"`;
            // in that case you need to check that dependent != null (if the group was not specified).
            System.out.printf(
                    "We are %sinstalling Artifactory version %s%n",
                    (dependent.install ? "" : "not "), dependent.version);
    
            return 0;
        }
    }